现在,我们将添加功能来读取filename命令行参数中指定的文件 。首先,我们需要一个示例文件对其进行测试:用来确保minigrep工作正常的最佳文件类型是:在多行上包含少量文本并带有重复单词的文件。清单12-3的一首埃米莉·狄金森诗很不错!在项目的根目录下创建一个名为poem.txt的文件 ,然后输入一首诗“ I'm Nobody!你是谁?”
档名:poem.txt
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 frogTo tell your name the livelong dayTo an admiring bog!
清单12-3:Emily Dickinson的一首诗很好地说明了这一点
放置好文本后,编辑src / main.rs并添加代码以读取文件,如清单12-4所示。
文件名:src / main.rs
use std::env;use std::fs;fn main() { // --snip-- println!("In file {}", filename); let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); println!("With text:{}", contents);}
代码清单12-4:读取第二个参数指定的文件的内容
首先,我们添加另一条use语句以引入标准库的相关部分:我们需要std::fs处理文件。
在中main,我们添加了一条新语句:fs::read_to_string使用 filename,打开该文件,然后返回Result文件内容中的a。
在该语句之后,我们再次添加了一条临时println!语句,该语句将contents在读取文件后显示的值,因此我们可以检查程序是否正常运行。
让我们以任何字符串作为第一个命令行参数(因为我们尚未实现搜索部分)并将poem.txt文件作为第二个参数运行此代码:
$ cargo run the poem.txt Compiling minigrep v0.1.0 (file:///projects/minigrep) Finished dev [unoptimized + debuginfo] target(s) in 0.0s Running `target/debug/minigrep the poem.txt`Searching for theIn file poem.txtWith 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 frogTo tell your name the livelong dayTo an admiring bog!
大!代码读取并打印了文件的内容。但是代码有一些缺陷。该main功能具有多种职责:通常,如果每个功能仅负责一个构想,则功能会更清晰,更易于维护。另一个问题是我们没有尽力处理错误。该程序仍然很小,因此这些缺陷不是什么大问题,但是随着程序的发展,将很难对其进行彻底修复。最好在开发程序时尽早开始重构,因为重构少量代码要容易得多。接下来,我们会做。