- 新增 mkdir、ls、mv、rm、touch、cat 等常用命令的实现 - 支持命令行参数解析和错误处理 - 使用模块化设计,便于后续扩展 - 添加 Cargo.toml 文件,定义项目依赖 - 创建 .gitignore 文件,忽略不必要的文件和目录
34 lines
879 B
Rust
34 lines
879 B
Rust
use std::fs;
|
|
use std::path::Path;
|
|
|
|
pub fn execute(args: &[String]) {
|
|
// 检查参数数量
|
|
if args.is_empty() {
|
|
eprintln!("用法: cat <文件名>");
|
|
return;
|
|
}
|
|
|
|
// 遍历所有传入的文件名
|
|
for arg in args {
|
|
let path = Path::new(arg);
|
|
|
|
// 检查文件是否存在
|
|
if !path.exists() {
|
|
eprintln!("错误: 文件 '{}' 不存在", arg);
|
|
continue; // 跳过不存在的文件
|
|
}
|
|
|
|
// 尝试读取文件内容
|
|
match fs::read_to_string(path) {
|
|
Ok(contents) => {
|
|
// 打印文件内容
|
|
println!("内容来自文件 '{}':", arg);
|
|
println!("{}", contents);
|
|
}
|
|
Err(e) => {
|
|
eprintln!("读取文件 '{}' 时出错: {}", arg, e); // 输出读取错误
|
|
}
|
|
}
|
|
}
|
|
}
|