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

心不动则不痛 提交于 2020-08-07 02:37:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!