rust - 为什么这个锈代码在没有文件的时候挂了,但是在文件存在的时候运行正常?
问题描述
我有一些 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)
}
}
推荐阅读
- c# - 如何修复 json 错误期望'STRING',得到'}'
- python - /snippets/1/ 处的类型错误
- macos - 在插入和搜索正常路径的尝试中,ascii 1-31 值得考虑吗?
- spring-boot - 弹簧MVC;未显示验证表单的错误消息
- react-native - iOS上的React Native相机显示空白屏幕
- sql - 将日期值(动态变化)传递给存储过程的输入参数
- laravel - 如何扩展 OctoberCMS 插件以发送 Slack 通知?
- android - 如何获取上一个活动的名称并存储在变量中
- kubernetes - 使用 Kubernetes 或更简单的编排工具
- swiftui - 如何在 SwiftUI 中将 print() 打印到 Xcode 控制台?