Write A String To A File Making Directories In Rust
use std::fs;
use std::path::PathBuf;
fn main() {
let path = PathBuf::from("/Users/alan/Desktop/some/new/folders/file.txt");
let content = "the quick brown fox".to_string();
let _ = write_file_mkdir(&path, &content);
}
// TODO: Return better errors
fn write_file_with_mkdir(path: &PathBuf, content: &str) -> Result<(), String> {
match path.parent() {
Some(parent_dir) => match fs::create_dir_all(parent_dir) {
Ok(_) => {
match fs::write(path, content) {
Ok(_) => Ok(()),
Err(e) => Err(e.to_string())
}
},
Err(e) => Err(e.to_string())
},
None => Err("Could not make directory".to_string())
}
}
Output:
-- end of line --