File io 在文本文件中添加新行的最佳变体是什么?

File io 在文本文件中添加新行的最佳变体是什么?,file-io,rust,File Io,Rust,我使用此代码在文件末尾追加一行新行: let text = "New line".to_string(); let mut option = OpenOptions::new(); option.read(true); option.write(true); option.create(true); match option.open("foo.txt") { Err(e) => { println!("Error"); } Ok(mut f)

我使用此代码在文件末尾追加一行新行:

let text = "New line".to_string();

let mut option = OpenOptions::new();
option.read(true);
option.write(true);
option.create(true);

match option.open("foo.txt") {
    Err(e) => {
        println!("Error");
    }
    Ok(mut f) => {
        println!("File opened");
        let size = f.seek(SeekFrom::End(0)).unwrap();
        let n_text = match size {
            0 => text.clone(),
            _ => format!("\n{}", text),
        };
        match f.write_all(n_text.as_bytes()) {
            Err(e) => {
                println!("Write error");
            }
            Ok(_) => {
                println!("Write success");
            }
        }

        f.sync_all();
    }
}
这很有效,但我觉得太难了。我找到了
option.append(true)
,但如果我使用它而不是
选项。write(true)我得到“写入错误”。

使用是附加到文件的最清晰的方式:

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);
    }
}
从1.8.0()开始,
append(true)
意味着
write(true)
。这应该不再是个问题了


在Rust 1.8.0之前,您必须同时使用写入
追加
——第一种方法允许您将字节写入文件,第二种方法指定将写入字节的位置。

与问题本身无关,但
。to_owned()
。to_string()
更快,并且是首选的替代方案,除非您想严格限制某些Show实现类型。谢谢。我将使用它。因为,
.to\u string()
.to\u owned()
一样快。