file_operation/write/sync/
fn.rs

1use std::fs::{OpenOptions, create_dir_all};
2use std::io::{Error, Write};
3
4/// Writes content to a file.
5///
6/// # Arguments
7///
8/// - `&str` - The path to the file.
9/// - `&[u8]` - The content to write.
10///
11/// # Returns
12///
13/// - `Result<(), std::io::Error>` - Ok if successful, Err with error details otherwise.
14pub fn write_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
15    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
16        create_dir_all(parent_dir)?;
17    }
18    OpenOptions::new()
19        .write(true)
20        .create(true)
21        .truncate(true)
22        .open(file_path)
23        .and_then(|mut file| file.write_all(content))
24}
25
26/// Appends content to a file.
27///
28/// # Arguments
29///
30/// - `&str` - The path to the file.
31/// - `&[u8]` - The content to append.
32///
33/// # Returns
34///
35/// - `Result<(), std::io::Error>` - Ok if successful, Err with error details otherwise.
36pub fn append_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
37    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
38        create_dir_all(parent_dir)?;
39    }
40    OpenOptions::new()
41        .write(true)
42        .create(true)
43        .append(true)
44        .open(file_path)
45        .and_then(|mut file| file.write_all(content))
46}