Lesson 12

File Input and Output

Read from and write to text files using the standard library.

Learning objectives

Writing Files

Rust’s standard library includes tools for file operations. For simple cases, std::fs::write can write text into a file.

Reading Files

std::fs::read_to_string can read a text file into a String.

Practical Use

File input and output are useful for reports, logs, configuration files, and small data storage tasks.

Example code

use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    fs::write("notes.txt", "Learning Rust step by step")?;

    let content = fs::read_to_string("notes.txt")?;
    println!("File content: {}", content);

    Ok(())
}
Practice task: Write a program that saves three lines of text into a file and reads them back.