CodeBlanks Logo Icon CodeBlanks

Writing a file

Write a file with std::fs::write.

Writing files

fs::write creates the file or overwrites it. To write piece by piece, File::create and the Write trait are used; the writeln! macro can write to files too:

use std::fs::File;
use std::io::Write;

let mut f = File::create("sayilar.txt")?;
for i in 1..=3 {
    writeln!(f, "{i}")?;
}

To use write!/writeln!, std::io::Write must be in scope. The file closes automatically when f goes out of scope.

Buffered writing

Many small writes mean many calls to the operating system. BufWriter collects writes in memory and sends them in bulk:

use std::io::{BufWriter, Write};

let f = File::create("buyuk.txt")?;
let mut w = BufWriter::new(f);
for i in 0..10_000 {
    writeln!(w, "{i}")?;
}
w.flush()?;   // send the remaining buffer and catch the error

BufWriter also flushes when dropped, but an error at that moment is ignored; that's why an explicit flush is recommended.

Practice Write numbers

Open sayilar.txt in the temp folder with File::create and write the numbers 1 to 3 with writeln!. Read the file back and print its lines joined with commas.

Starter code

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

fn main() {
    // buraya yaz
}

Sample solution

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

fn main() -> io::Result<()> {
    let yol = env::temp_dir().join("sayilar.txt");
    {
        let mut f = File::create(&yol)?;
        for i in 1..=3 {
            writeln!(f, "{}", i)?;
        }
    }
    let icerik = fs::read_to_string(&yol)?;
    let parcalar: Vec<&str> = icerik.lines().collect();
    println!("{}", parcalar.join(","));
    Ok(())
}

Expected output

1,2,3

Questions and answers

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

1 What does <code>File::create</code> do with an existing file?

  • Errors
  • Makes a backup
  • Erases its content (truncates it to zero length) Correct answer
  • Appends to the end

Explanation: To protect an existing file, use File::create_new (new file only) or OpenOptions with append.

2 Write a line

Question
let mut f = File::create("sayilar.txt")?;
____(f, "{}", 42)?;
Answer
let mut f = File::create("sayilar.txt")?;
writeln!(f, "{}", 42)?;

Explanation: writeln! writes a line to any target implementing Write.

3 Operation and effect

Term Meaning
fs::write Creates or overwrites
File::create Opens an empty file
BufWriter::new(f) Bulk writing
w.flush() Flushes the buffer

All lessons in Intermediate