RRust By Example
intermediateFile I/O

File Write

Write files with std::fs.

File Write

Write files with std::fs.

Difficulty

Intermediate

Code

rust
use std::fs;
use std::io::Write;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // write string to file
    fs::write("output.txt", "Hello, file!")?;

    // write with BufWriter for performance
    let mut file = fs::File::create("output2.txt")?;
    writeln!(file, "line 1")?;
    writeln!(file, "line 2")?;

    println!("files written");
    Ok(())
}

Explanation

This example demonstrates how to use file write in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the file-io category to build a complete understanding of this topic.

More File I/O Examples