Rust
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.
Exercise 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.
Show example solution
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(())
}
Test yourself
-
What does <code>File::create</code> do with an existing file?
- Errors
- Makes a backup
- Erases its content (truncates it to zero length)
- Appends to the end
Show answer
Erases its content (truncates it to zero length) — To protect an existing file, use File::create_new (new file only) or OpenOptions with append.
-
Write a line
let mut f = File::create("sayilar.txt")?;
____(f, "{}", 42)?;
Show answer
let mut f = File::create("sayilar.txt")?;
writeln!(f, "{}", 42)?;
-
Operation and effect
- fs::write
- Creates or overwrites
- File::create
- Opens an empty file
- BufWriter::new(f)
- Bulk writing
- w.flush()
- Flushes the buffer
Next lesson: Append mode