蓝色天空网mbsky.com · 知识 · 实践 · 创造Rust · 本地阅读预览
教程 / 后端开发 / Rust

Rust 文件与 IO

核对 Rust std::env::args 命令行参数遍历、std::io::stdin 按行读取、std::fs 一次性与缓冲流式文件读写,以及 OpenOptions 追加与读写权限配置。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

命令行参数与标准输入读取

与 C/Java 通过 `main` 形参传递参数不同,Rust 的 `main` 函数不带参数,需借助 `std::env::args()` 获取命令行参数迭代器。直接打印 `{:?}` 可看到内部包裹着可执行文件路径(第 0 项),实际开发中通常用 `for arg in std::env::args()` 逐项遍历;在编辑器调试配置(如 `launch.json`)的 `"args": ["first", "second"]` 中或在终端直接传参,均可让程序依次读取程序路径、`first` 与 `second`。

标准输入由 `std::io::stdin()`(返回 `std::io::Stdin` 句柄)提供:调用 `stdin().read_line(&mut str_buf)` 将终端输入的一整行(保留末尾换行符)追加到可变 `String` 缓冲区,并返回 `Result<usize, io::Error>`,因此常配合 `.expect(...)` 或 `?` 处理异常;若在 IDE 调试面板交互受限,可直接在终端运行编译产物。由于标准库不直接按格式扫描数字,通常先读入字符串,再调用 `.trim().parse::<i32>()` 解析。本站离线校验器核对了参数遍历、`read_line` 换行保留及整数解析。

一次性读取与缓冲流式读取文件

对内存可完全容纳的中小文件,`std::fs` 提供了极其简洁的一次性读取接口:`fs::read_to_string(path)` 将 UTF-8 文本文件读入 `String`(例如读取 `This is a text file.`);处理二进制文件则使用 `fs::read(path)` 返回 `Vec<u8>` 字节序列(上述文本对应 20 个 ASCII 字节 `[84, 104, 105, ...]`)。

面对体积远超内存的大文件或底层字节流,需使用 `std::fs::File::open(path)` 以只读方式打开文件句柄,引入 `std::io::prelude::*`(包含 `Read`/`Write` trait,若 IDE 提示方法不存在应先核对标准库 trait 导入),再利用定长字节数组缓冲区(如 `let mut buffer = [0u8; 5];`)反复调用 `file.read(&mut buffer)` 分块拉取(前两批各 5 字节分别为 `[84, 104, 105, 115, 32]` 与 `[105, 115, 32, 97, 32]`)。Rust 的 `File` 无需手动 `close()`,句柄离开作用域时会借助 RAII(`Drop` trait)自动关闭底层文件描述符。

文件写入与 OpenOptions 权限组合

文件写入同样区分一次性写入与流式写入:`fs::write(path, "FROM RUST PROGRAM")` 与 `File::create(path)` 配合 `file.write(b"FROM RUST PROGRAM")` 效果等价——若文件不存在则新建,若已存在则会**立即截断清空原内容**,操作大文件前务必谨慎;同时流式读写句柄必须绑定在 `mut` 变量上才能调用 `Read`/`Write` 方法。

`File` 没有直接的 `append` 静态方法,细粒度打开模式须通过 `std::fs::OpenOptions::new()` 链式配置:设置 `.append(true).open(path)?` 后写入 `b" APPEND WORD"` 可在文件末尾追加为 `FROM RUST PROGRAM APPEND WORD`;若改用 `.read(true).write(true).open(path)?` 打开而不截断,初始文件游标位于偏移 `0`,写入 5 字节 `b"COVER"` 会原地覆写头部 5 字节而保留后续字节,使文件内容变为 `COVERRUST PROGRAM APPEND WORD`。本站离线脚本已在 `tempfile.TemporaryDirectory` 真实文件系统上完整复现并核对上述全部读写序列。

运行离线 Python 校验:Rust 命令行参数、stdin 行读、真实临时文件流式读写与 OpenOptions 覆写

python · 阅读源码
"""Offline Rust semantic verifier for Chapter 23: File & IO (args, stdin, fs read/write, streaming, OpenOptions)."""
import io
import json
from pathlib import Path
import tempfile


def run_cases() -> list[dict]:
    cases = []

    # Case 1: std::env::args() iteration and std::io::stdin().read_line() buffer semantics
    sim_args = ["target/debug/greeting.exe", "first", "second"]
    stdin_stream = io.StringIO("HELLO_RUST\n42\n")
    line_buf = stdin_stream.readline()
    num_line = stdin_stream.readline()
    parsed_num = int(num_line.strip())
    actual_1 = {
        "arg_count": len(sim_args),
        "user_args": sim_args[1:],
        "read_line_preserves_newline": line_buf == "HELLO_RUST\n",
        "parsed_int_from_line": parsed_num,
    }
    expected_1 = {
        "arg_count": 3,
        "user_args": ["first", "second"],
        "read_line_preserves_newline": True,
        "parsed_int_from_line": 42,
    }
    cases.append(dict(
        name="cli_args_and_stdin_read_line",
        summary="Verify env::args() indexing/iteration and stdin().read_line() newline retention + parse",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    with tempfile.TemporaryDirectory() as tmp:
        text_path = Path(tmp) / "text.txt"
        text_path.write_text("This is a text file.", encoding="utf-8")

        # Case 2: fs::read_to_string, fs::read (Vec<u8>), and 5-byte buffered File::read stream
        full_str = text_path.read_text(encoding="utf-8")
        full_bytes = list(text_path.read_bytes())
        with text_path.open("rb") as fh:
            chunk1 = list(fh.read(5))
            chunk2 = list(fh.read(5))
        actual_2 = {
            "read_to_string": full_str,
            "byte_len": len(full_bytes),
            "first_5_bytes": chunk1,
            "second_5_bytes": chunk2,
        }
        expected_2 = {
            "read_to_string": "This is a text file.",
            "byte_len": 20,
            "first_5_bytes": [84, 104, 105, 115, 32],
            "second_5_bytes": [105, 115, 32, 97, 32],
        }
        cases.append(dict(
            name="fs_read_to_string_bytes_and_stream",
            summary="Verify real temp-file text read, u8 byte vector [84,104,...], and two 5-byte streaming reads",
            expected=expected_2,
            actual=actual_2,
            passed=actual_2 == expected_2,
        ))

        # Case 3: fs::write / File::create truncate, OpenOptions::append, and OpenOptions read+write in-place overwrite
        text_path.write_bytes(b"FROM RUST PROGRAM")
        after_write = text_path.read_text(encoding="utf-8")

        # OpenOptions::new().append(true)
        with text_path.open("ab") as fh:
            fh.write(b" APPEND WORD")
        after_append = text_path.read_text(encoding="utf-8")

        # OpenOptions::new().read(true).write(true) -> cursor starts at 0, overwrites prefix without truncating
        with text_path.open("r+b") as fh:
            fh.write(b"COVER")
        after_cover = text_path.read_text(encoding="utf-8")

        actual_3 = {
            "after_create_write": after_write,
            "after_append": after_append,
            "after_rw_cover": after_cover,
        }
        expected_3 = {
            "after_create_write": "FROM RUST PROGRAM",
            "after_append": "FROM RUST PROGRAM APPEND WORD",
            "after_rw_cover": "COVERRUST PROGRAM APPEND WORD",
        }
        cases.append(dict(
            name="fs_write_append_and_open_options_rw",
            summary="Verify truncate write, append mode, and read+write offset-0 overwrite (COVERRUST PROGRAM APPEND WORD)",
            expected=expected_3,
            actual=actual_3,
            passed=actual_3 == expected_3,
        ))

    return cases


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
        "cases": run_cases(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 env::args 与 stdin 换行保留、20 字节 ASCII 与两批 5 字节分块读取,以及截断写 -> append -> read+write 原地覆写得到 COVERRUST PROGRAM APPEND WORD。
运行离线 Python 校验:Rust 命令行参数、stdin 行读、真实临时文件流式读写与 OpenOptions 覆写

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:c0ddf7c13ef76104961eff3133479c9c967c15ef71654e8bcc7e702ffeb73cfa

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Rust 文件与 IO实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:b2b71358931f43dfa6780f47c6e16cedb4bb4a30a1f853726cd3335343be9c68

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 OpenOptions::new().read(true).write(true).open(...) 后直接写入 5 字节 b"COVER" 不会清空文件原有内容,而是变成 COVERRUST PROGRAM...?

展开参考解答

只配置 read(true).write(true) 而未设置 truncate(true) 或 append(true) 时,文件会保留原有内容且读写游标位于文件开头偏移 0,因此写入的 5 字节会从头部原地覆盖前 5 字节(FROM )。

规范与官方依据