简体   繁体   English

如果文件不存在,我如何读取文件或将其连同其目录一起创建?

[英]How can I read a file or create it along with its directory if it doesn't exist?

I want to read a file into a vector, but if it doesn't exist, I don't want the program to panic.我想将文件读入向量,但如果它不存在,我不希望程序恐慌。 Instead, I want the file to be created (with empty contents).相反,我希望创建文件(内容为空)。 If the directory doesn't exist, I want it to be created, too.如果该目录不存在,我也希望创建它。

How can I do this automatically in Rust?如何在 Rust 中自动执行此操作?

This is my current code:这是我当前的代码:

pub fn read(path: &str) -> Vec<String> {
    let file = File::open(path).unwrap();
    let reader = BufReader::new(file);
    let mut history = Vec::new();
    for line in reader.lines() {
        history.push(line.unwrap());
    }
    history
}

Ingredients:原料:

If you do not want your program to panic, unwrap is not your friend, as it panics as soon as you call it on an Err .如果您不希望您的程序恐慌, unwrap不是您的朋友,因为一旦您在Err上调用它,它就会恐慌。 Now, given that file operations - generally speaking - could always go wrong, you must decide what to do if a file operation fails.现在,考虑到文件操作 - 一般而言 - 可能总是go 错误,您必须决定如果文件操作失败该怎么办。 Simply returning an empty Vec without any associated file?只是返回一个没有任何关联文件的空Vec

Regarding this, error handling , in particular with Result is a worthwhile read.关于这一点,错误处理,尤其是Result是值得一读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM