为什么这个 rust 代码在没有文件时会挂起,而在文件存在时运行正常?

Why does this rust code hang when there is no file, but runs fine when the file exists?

我有一些 Rust 代码可以从文件中读取行,然后打印它们。如果指定的文件名不存在,它会创建一个文件。如果文件存在,它会正常退出,并读取行,但如果文件不存在,它会创建文件,什么都不做。文件不存在程序不退出

use std::fs::File;
use std::io::{self, BufRead};
use std::io::ErrorKind;

fn file_to_vec(filename: &str) -> Vec<String> { 
    let file_in = File::open(filename);
    let file_in = match file_in {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create(filename) {
                Ok(file) => {println!("Created file: {}", filename); file},
                Err(e) => panic!("Problem creating the file: {:?}", e),
            },
            other_error => {
                panic!("Problem opening the file: {:?}", other_error)
            }
        },
    };
    let file_reader = io::BufReader::new(file_in); 
    file_reader.lines().filter_map(io::Result::ok).collect()
} 


fn main() {
    let stuff = file_to_vec("stuff.txt");
    for thing in stuff {
        println!("{}", thing)
    }
}

发生这种情况是因为 File::create 打开一个没有 read 标志的文件,因此无法读取。

我用 OpenOptions 修复了它:

use std::fs::{File, OpenOptions};
use std::io::ErrorKind;
use std::io::{self, BufRead};

fn file_to_vec(filename: &str) -> Vec<String> {
    let file_in = File::open(filename);
    let file_in = match file_in {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => {
                let mut options = OpenOptions::new();
                options.read(true).write(true).create(true);
                match options.open(filename) {
                    Ok(file) => {
                        println!("Created file: {}", filename);
                        file
                    }
                    Err(e) => panic!("Problem creating the file: {:?}", e),
                }
            }
            other_error => {
                panic!("Problem opening the file: {:?}", other_error)
            }
        },
    };
    let file_reader = io::BufReader::new(file_in);
    file_reader.lines().map(Result::unwrap).collect()
}

fn main() {
    let stuff = file_to_vec("stuff.txt");
    for thing in stuff {
        println!("{}", thing)
    }
}