问题
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(())
}
回答1:
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();
来源:https://stackoverflow.com/questions/59046312/how-can-i-create-a-file-and-its-parent-directories-using-a-single-method-in-rust