file_operation/write/sync/
fn.rs

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