3. 文件读取与写入
任务说明
实现一个命令行程序,读取指定文本文件的内容,统计其中单词的数量,并将统计结果写入另一个文件。程序需要处理文件不存在、读取失败等基本错误场景。
实现方案
使用Rust标准库中的std::fs模块完成文件读写操作。通过fs::read_to_string读取整个文件内容,使用split_whitespace方法按空白字符分割文本并统计单词数,最后通过fs::write将结果写入目标文件。程序接收两个命令行参数:输入文件路径和输出文件路径。
代码实现
use std::env;
use std::fs;
use std::process;
fn main() {
// 收集命令行参数
let args: Vec<String> = env::args().collect();
// 检查参数数量是否正确(程序名 + 输入文件 + 输出文件)
if args.len() != 3 {
eprintln!("用法: {} <输入文件> <输出文件>", args[0]);
process::exit(1);
}
let input_path = &args[1];
let output_path = &args[2];
// 读取输入文件内容
let content = match fs::read_to_string(input_path) {
Ok(text) => text,
Err(err) => {
eprintln!("读取文件 '{}' 失败: {}", input_path, err);
process::exit(1);
}
};
// 统计单词数:按空白字符分割并计数
let word_count = content.split_whitespace().count();
// 构造输出内容
let output = format!("文件 '{}' 中的单词数: {}\n", input_path, word_count);
// 写入输出文件
if let Err(err) = fs::write(output_path, output) {
eprintln!("写入文件 '{}' 失败: {}", output_path, err);
process::exit(1);
}
println!("成功将统计结果写入 '{}'", output_path);
}
编译与运行
创建新的Rust项目并替换src/main.rs为上述代码:
cargo new word_count
cd word_count
# 将上述代码复制到 src/main.rs
准备一个测试输入文件input.txt,内容示例:
Rust is a systems programming language
that runs blazingly fast, prevents segfaults,
and guarantees thread safety.
运行程序:
cargo run -- input.txt output.txt
验证方法
程序执行后,检查以下判定标准:
- 终端输出
成功将统计结果写入 'output.txt',退出码为0; - 查看
output.txt文件内容,应包含文件 'input.txt' 中的单词数: 15(上述示例文本按空白分割后共15个单词); - 当输入文件不存在时,程序应输出错误信息并以非零退出码结束;
- 当命令行参数不足或多余时,程序应打印用法提示并退出。