Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a file and its parent directories using a single method in Rust?

Tags:

file

rust

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(())
}
like image 948
fabiim Avatar asked Nov 26 '19 08:11

fabiim


Video Answer


1 Answers

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();
like image 165
Roger Lipscombe Avatar answered Sep 20 '22 08:09

Roger Lipscombe