首页 > 解决方案 > 为什么这个锈代码在没有文件的时候挂了,但是在文件存在的时候运行正常?

问题描述

我有一些 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)
    }
}

标签: rustfile-iofilesystems

解决方案


发生这种情况是因为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)
    }
}

推荐阅读