我们实现从变量file_path获取文件路径,然后从该文件中读取信息。首先我们需要一个文本文件进行测试;文件名是poem.txt,该文件包含多行文本并有一些重复的单词。如下所示的一首艾米丽.狄更斯的诗:
bash
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!
这个文件需要保存到项目的根目录内。修改代码读取文件中的信息:
rust
use std::env;
use std::fs;
fn main() {
let args:Vec<String> = env::args().collect();
//dbg!(args);
let query = &args[1];
let file_path = &args[2];
println!("要查找的字符串是{query}");
println!("在{file_path}文件中");
let contents = fs::read_to_string(file_path).expect("无法读取这个文件{file_path}");
println!("文件中的内容是:\n{contents}");
}
首先使用use引入标准库中相关模块,以便我们可以使用std::fs来处理文件操作。
在主函数中我们使用fs::read_to_string函数并传入file_path参数,打开该文件并返回std::io::Result<String>类型的文件内容。
然后再次使用println函数向屏幕上输出文件内容信息,以便我们可以检核程序是否运行正常。
运行这段代码,第一个参数随便输入一些信息,因为还没有实现搜索字符串的功能,第二个参数为poem.txt,是我们刚刚创建的文本文件,并保存到项目根目录的位置上。运行结果如下所示:
rust
cargo run -- test poem.txt
warning: `C:\Users\刘海涛\.cargo\config` is deprecated in favor of `config.toml`
|
= help: if you need to support cargo 1.38 or earlier, you can symlink `config` to `config.toml`
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
Running `target\debug\lession14_001.exe test poem.txt`
要查找的字符串是test
在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 frog
To tell your name the livelong day
To an admiring bog!
很好这段代码可以去取文件中的内容并显示。但是代码还有很多缺陷,此时,主函数有多个任务:通常来说,如果每一个功能只负责一个主题,则代码及清晰也容易理解。还有一些问题是我们没有考虑到异常情况和对应的错误处理。因为这个程序还是非常小,这些缺陷并不是很大的问题,但是随着代码的增长,它将很难使代码变得清晰。在程序开发的早期进行代码重构将是非常可取的,因为更小的代码量更容易重构。