What is the best variant for appending a new line in a text file?

后端 未结 1 349
心在旅途
心在旅途 2021-01-01 11:27

I am using this code to append a new line to the end of a file:

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

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


        
相关标签:
1条回答
  • 2021-01-01 12:27

    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);
        }
    }
    

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

    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.

    0 讨论(0)
提交回复
热议问题