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

fs::write writes strings to files.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

More File I/O Examples