且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在文本文件中添加新行的***变体是什么?

更新时间:2023-12-01 13:55:28

使用 OpenOptions::append 是追加到文件的最清晰方法:

Using OpenOptions::append is the clearest way to append to a file:

use std::fs::OpenOptions;
use std::io::prelude::*;

fn main() {
    let mut file = OpenOptions::new()
        .write(true)
        .append(true)
        .open("my-file")
        .unwrap();

    if let Err(e) = writeln!(file, "A new line!") {
        eprintln!("Couldn't write to file: {}", e);
    }
}

从Rust 1.8.0开始( commit )和 RFC 1252 append(true)表示write(true).这应该不再是问题了.

As of Rust 1.8.0 (commit) and RFC 1252, append(true) implies write(true). This should not be a problem anymore.

在Rust 1.8.0之前,您必须同时使用 writeappend —第一个允许您将字节写入文件,第二个允许将字节写入位置.

Before Rust 1.8.0, you must use both write and append — the first one allows you to write bytes into a file, the second specifies where the bytes will be written.