Rust Lesson 33 – File Handling | Dataplexa

File Handling in Rust

In this lesson, you will learn how to read from and write to files in Rust. File handling is an essential skill for building real-world applications.

Rust provides safe and powerful APIs for working with files while preventing common errors such as memory leaks and data races.


Why File Handling Is Important

File handling allows programs to:

  • Store data permanently
  • Read configuration files
  • Process logs and reports
  • Exchange data between programs

Rust ensures file operations are safe and explicit.


Rust File Handling Basics

Rust file handling is provided through the std::fs and std::io modules.

To work with files, you commonly use:

  • File for opening files
  • read_to_string for reading content
  • write for writing data

Importing Required Modules

Before working with files, import the necessary modules.

use std::fs;
use std::fs::File;
use std::io::{self, Read, Write};

Reading a File Using read_to_string

The easiest way to read a file is using fs::read_to_string.

use std::fs;

fn main() {
    let content = fs::read_to_string("example.txt")
        .expect("Failed to read file");

    println!("{}", content);
}

This reads the entire file into a string.


Reading a File Using File and Read Trait

For more control, you can open a file and read it manually.

use std::fs::File;
use std::io::Read;

fn main() {
    let mut file = File::open("example.txt").expect("Cannot open file");
    let mut content = String::new();

    file.read_to_string(&mut content).expect("Cannot read file");

    println!("{}", content);
}

This approach is useful for advanced scenarios.


Writing to a File

You can write data to a file using fs::write.

use std::fs;

fn main() {
    fs::write("output.txt", "Hello, Rust!")
        .expect("Failed to write file");
}

This creates the file if it does not exist.


Writing Using File and Write Trait

For more control, use File::create and the Write trait.

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

fn main() {
    let mut file = File::create("data.txt").expect("Cannot create file");

    file.write_all(b"Rust file handling example")
        .expect("Write failed");
}

Appending to a File

To append data, use OpenOptions.

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let mut file = OpenOptions::new()
        .append(true)
        .open("data.txt")
        .expect("Cannot open file");

    file.write_all(b"\nNew line added")
        .expect("Append failed");
}

Error Handling in File Operations

Rust encourages explicit error handling using Result.

use std::fs;

fn main() -> Result<(), std::io::Error> {
    let content = fs::read_to_string("example.txt")?;
    println!("{}", content);
    Ok(())
}

This approach makes code cleaner and safer.


Why Rust File Handling Is Safe

Rust ensures:

  • No use-after-free errors
  • Explicit error handling
  • Clear ownership of file handles

This makes Rust ideal for systems that require reliability.


📝 Practice Exercises


Exercise 1

Read a text file and print its content.

Exercise 2

Write a message to a new file.

Exercise 3

Append a new line to an existing file.

Exercise 4

Handle file errors using Result.


✅ Practice Answers


Answer 1

let data = std::fs::read_to_string("file.txt").unwrap();
println!("{}", data);

Answer 2

std::fs::write("new.txt", "Hello Rust").unwrap();

Answer 3

use std::fs::OpenOptions;
use std::io::Write;

let mut file = OpenOptions::new().append(true).open("new.txt").unwrap();
file.write_all(b"\nAppended").unwrap();

Answer 4

fn main() -> Result<(), std::io::Error> {
    let text = std::fs::read_to_string("file.txt")?;
    println!("{}", text);
    Ok(())
}

What’s Next?

In the next lesson, you will learn about Working with JSON in Rust, including serialization and deserialization using serde.