Can I open a file creating it and its parent directories using OpenOptions
or a similar single method?
This only creates a new file, it does not work if my path includes non-existing directories:
pub fn save_file(file_path: String) -> Result<(), Error> {
let mut db_file = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)?;
db_file.write_all(b"some content")?;
Ok(())
}
I couldn't find a single method to do this, but here's how to create the parent directory (etc.) for a given file in two (if you don't count let path =
...).
let path = std::path::Path::new("/home/roger/foo/bar/baz.txt");
let prefix = path.parent().unwrap();
std::fs::create_dir_all(prefix).unwrap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With