file_operation/write/sync/
fn.rs1use std::fs::{OpenOptions, create_dir_all};
2use std::io::{Error, Write};
3
4pub 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
26pub 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}