57

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

It works, but I think it's too difficult. I found option.append(true);, but if I use it instead of option.write(true); I get "Write error".

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Aleksandr
  • 1,755
  • 3
  • 13
  • 8
  • 6
    Unrelated to the question itself, but `.to_owned()` is faster than `.to_string()`, and is the preferred alternative unless you want to stringify some Show-implementing type. – llogiq Jun 06 '15 at 16:24
  • 1
    Thanks. I will use it. – Aleksandr Jun 07 '15 at 15:19
  • 7
    Since [specialize ToString for str](https://github.com/rust-lang/rust/pull/32586), `.to_string()` is as fast as `.to_owned()`. – AurevoirXavier Sep 06 '18 at 10:32

1 Answers1

100

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Is it possible to "append" to the top as well? (so adding a line **above** the first line) – Corel Aug 03 '21 at 15:30
  • 3
    @Corel [How can I prepend a line to the beginning of a file?](https://stackoverflow.com/q/43441166/155423) – Shepmaster Aug 03 '21 at 15:32
  • What's the behavior of just the write mode (not appending) on EOF? –  Jan 05 '22 at 19:52
  • 1
    @CtrlAltF2 From [`OpenOptions::write`](https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.write) "*If the file already exists, any write calls on it will overwrite its contents, without truncating it.*" – kmdreko Dec 27 '22 at 19:23
  • I'm trying to use this solution to accomplish the _opposite_ of what OP is discussing, I'd like to simply write to a file multiple times, without appending. My text file doesn't exist before the code is ran, so I want my code to create the file, and then non-additively write to it. Here's how I instantiate my file object: ```rust let mut output_txt_file = OpenOptions::new().write(true).create(true).append(false).open(output_txt_filename).unwrap(); ``` This doesn't work though, as despite setting append to false, the text file continually grows with each successive call to `writeln`. – Raleigh L. Feb 15 '23 at 06:07
  • 1
    @RaleighL. in that case, you'd want to [`rewind`](https://doc.rust-lang.org/stable/std/io/trait.Seek.html#method.rewind) your file. – Shepmaster Apr 14 '23 at 21:09