CodeBlanks Logo Icon CodeBlanks

Append mode

Learn append mode with OpenOptions.

Append mode

To add to the end of an existing file, OpenOptions is used. Which operations are allowed is stated one by one:

use std::fs::OpenOptions;
use std::io::Write;

let mut f = OpenOptions::new()
    .append(true)    // add to the end
    .create(true)    // create if missing
    .open("gunluk.txt")?;
writeln!(f, "yeni kayıt")?;

It's ideal for log files: each run adds new lines without deleting the earlier ones.

Options

OpenOptions is the basis of the other opening methods:

File::open(y)    // = OpenOptions::new().read(true).open(y)
File::create(y)  // = .write(true).create(true).truncate(true)

OpenOptions::new().write(true).create_new(true).open(y)
// opens only if the file does NOT exist; AlreadyExists error otherwise

create_new is safe against race conditions where two programs try to create the same file at the same time.

Practice Log file

Write "a\n" to gunluk.txt in the temp folder with fs::write. Then open it twice in append mode with OpenOptions and add the line "b". Read the file and print its lines joined with |.

Starter code

main.rs
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let yol = env::temp_dir().join("gunluk.txt");
    fs::write(&yol, "a\n")?;
    for _ in 0..2 {
        let mut f = OpenOptions::new().append(true).create(true).open(&yol)?;
        writeln!(f, "b")?;
    }
    let icerik = fs::read_to_string(&yol)?;
    let s: Vec<&str> = icerik.lines().collect();
    println!("{}", s.join("|"));
    Ok(())
}

Expected output

a|b|b

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>OpenOptions::new().append(true).open(..)</code> do if the file doesn't exist?

  • Does nothing
  • Returns a NotFound error; create(true) is needed Correct answer
  • Creates the file
  • Panics

Explanation: In OpenOptions every behaviour must be asked for explicitly; the default is nothing.

2 Append

Question
let mut f = OpenOptions::new()
    .____(true)
    .create(true)
    .open("gunluk.txt")?;
Answer
let mut f = OpenOptions::new()
    .append(true)
    .create(true)
    .open("gunluk.txt")?;

Explanation: append(true) makes writes go to the end of the file.

3 Method and equivalent

Term Meaning
File::open read(true)
File::create write + create + truncate
append(true) Appends
create_new(true) Error if it exists

All lessons in Intermediate