MST

星途 面试题库

面试题:Rust命令行工具的复杂文件操作

编写一个Rust命令行工具,它接收两个文件名作为参数。第一个文件是源文件,第二个文件是目标文件。工具需要将源文件内容读取,对其中的每一行进行排序(按照字母顺序),然后将排序后的内容写入目标文件。同时需要考虑文件过大时的内存优化问题,并正确处理所有可能的I/O错误。
33.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fs::{self, File};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::process::exit;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 3 {
        eprintln!("Usage: {} <source_file> <target_file>", args[0]);
        exit(1);
    }

    let source_file = &args[1];
    let target_file = &args[2];

    let file = match File::open(source_file) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Failed to open source file: {}", e);
            exit(1);
        }
    };

    let reader = BufReader::new(file);
    let mut lines: Vec<String> = Vec::new();
    for line in reader.lines() {
        match line {
            Ok(l) => lines.push(l),
            Err(e) => {
                eprintln!("Failed to read line: {}", e);
                exit(1);
            }
        }
    }

    lines.sort();

    let file = match File::create(target_file) {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Failed to create target file: {}", e);
            exit(1);
        }
    };

    let mut writer = BufWriter::new(file);
    for line in lines {
        match writer.write_all(line.as_bytes()) {
            Ok(_) => match writer.write_all(b"\n") {
                Ok(_) => (),
                Err(e) => {
                    eprintln!("Failed to write line to target file: {}", e);
                    exit(1);
                }
            },
            Err(e) => {
                eprintln!("Failed to write line to target file: {}", e);
                exit(1);
            }
        }
    }

    match writer.flush() {
        Ok(_) => (),
        Err(e) => {
            eprintln!("Failed to flush writer: {}", e);
            exit(1);
        }
    }
}

上述代码实现了以下功能:

  1. 参数检查:确保程序接收两个文件名作为参数。
  2. 文件读取:打开源文件并逐行读取内容,同时处理读取过程中的错误。
  3. 内存优化:这里通过逐行读取文件内容到Vec<String>中,避免一次性将整个大文件读入内存。如果文件非常大,可以考虑使用更高级的分块处理策略。
  4. 排序:对读取的每一行按照字母顺序排序。
  5. 文件写入:将排序后的内容写入目标文件,并处理写入过程中的错误。
  6. 错误处理:对文件操作过程中可能出现的各种I/O错误进行处理,并打印错误信息后退出程序。