读取文件
现在,我们将添加功能来读取file_path
论点。首先,我们需要一个示例文件来测试它:我们将使用一个带有
多行少量文本,带有一些重复的单词。示例 12-3
有一首艾米莉·狄金森 (Emily Dickinson) 的诗会很有效!在项目的根目录下创建一个名为 poem.txt 的文件,然后输入诗歌 “I'm Nobody!
你是谁?
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
文本就位后,编辑 src/main.rs 并添加代码以读取文件,如 如示例 12-4 所示。
use std::env;
use std::fs;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let query = &args[1];
let file_path = &args[2];
println!("Searching for {query}");
println!("In file {file_path}");
let contents = fs::read_to_string(file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
首先,我们使用use
声明:我们需要std::fs
处理文件。
在main
、新语句fs::read_to_string
采用file_path
打开
该文件,并返回 type 为std::io::Result<String>
包含
文件的内容。
之后,我们再次添加一个临时的println!
打印值
之contents
读取文件后,我们可以检查程序是否
到目前为止。
让我们以任何字符串作为第一个命令行参数来运行这段代码(因为 我们还没有实现 searching 部分),poem.txt 文件作为 第二个参数:
$ cargo run -- the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
伟大!代码读取并打印文件的内容。但是代码
有一些缺陷。目前,main
函数具有多个
职责:一般来说,如果满足以下条件,则功能更清晰、更容易维护
每个函数只负责一个 IDEA。另一个问题是,我们是
没有尽我们所能处理错误。该程序仍然很小,因此这些
缺陷不是什么大问题,但随着程序的发展,修复会越来越困难
他们干净利落。最好在以下情况下尽早开始重构
开发程序,因为重构少量
法典。我们接下来会这样做。
本文档由官方文档翻译而来,如有差异请以官方英文文档(https://doc.rust-lang.org/)为准