Rust
December 2, 2026 10 min read

File Handling in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Is File Handling?

File handling means performing operations on files using a programming language.

Common file operations include:


Operation

Purpose

Create

Create a new file

Read

Read file contents

Write

Write data into a file

Append

Add data to an existing file

Delete

Remove a file

Rename

Change a file name

Copy

Copy a file

Metadata

Get information about a file

Rust provides the std::fs module for file operations.

2. Importing the File System Module

To work with files, import the standard file system module.

use std::fs;

The fs module provides functions for reading, writing, copying, renaming, and deleting files.

3. Creating and Writing a File

Rust provides the fs::write() function to create a file and write data into it.

Syntax:

fs::write("filename.txt", "content");

Example:

use std::fs;

fn main() {
fs::write("student.txt", "Student Name: Hemant")
.expect("Unable to write file");

println!("File created successfully!");
}

Output:

File created successfully!

A file named student.txt will be created in the program's current working directory.

Its contents will be:

Student Name: Hemant

Important: If the file already exists, fs::write() replaces its existing contents.

4. Reading a File

Rust provides fs::read_to_string() to read an entire text file into a String.

Example:

use std::fs;

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

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

Output:

Student Name: Hemant

Explanation:

  1. fs::read_to_string() reads the file.
  2. The file contents are returned as a String.
  3. expect() displays a custom panic message if reading fails.

5. Appending Data to a File

Sometimes you do not want to replace existing file contents. You want to add new information.

Rust provides OpenOptions for this purpose.

Example:

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

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

writeln!(file, "Course: Rust Programming")
.expect("Unable to write data");

println!("Data appended successfully!");
}

Updated file contents:

Student Name: Hemant
Course: Rust Programming

Explanation:

  1. OpenOptions::new() creates file-opening options.
  2. .append(true) opens the file in append mode.
  3. .open() opens the existing file.
  4. writeln!() writes a line and adds a newline.

Important: This example expects student.txt to exist. If you want to create it when missing, add .create(true):

let mut file = OpenOptions::new()
.append(true)
.create(true)
.open("student.txt")
.expect("Unable to open file");

6. Using File::create()

Rust also provides File::create() to create a file.

Example:

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

fn main() {
let mut file = File::create("hello.txt")
.expect("Unable to create file");

file.write_all(b"Hello Rust")
.expect("Unable to write file");

println!("File created!");
}

File contents:

Hello Rust

Important: File::create() truncates an existing file to zero length before writing.

7. Using File::open()

You can use File::open() to open an existing file for reading.

Example:

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

fn main() {
let mut file = File::open("hello.txt")
.expect("Unable to open file");

let mut content = String::new();

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

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

Output:

Hello Rust

Explanation:

  1. File::open() opens an existing file.
  2. String::new() creates an empty String.
  3. read_to_string() reads the file contents into that String.

8. Difference Between File::create() and File::open()


Method

Purpose

File::create()

Creates a file for writing; truncates an existing file

File::open()

Opens an existing file for reading

Use OpenOptions when you need more control over how a file is opened.

9. Understanding OpenOptions

OpenOptions allows you to specify different file-opening behaviours.

Example:

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

fn main() {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("data.txt")
.expect("Unable to open file");

file.write_all(b"Rust File Handling")
.expect("Unable to write");

println!("Operation completed!");
}

Common options:


Option

Purpose

.read(true)

Allows reading

.write(true)

Allows writing

.append(true)

Writes at the end of the file

.create(true)

Creates the file if it does not exist

.truncate(true)

Removes existing contents when opening for writing

.create_new(true)

Creates a new file and fails if it already exists

Note: append(true) and truncate(true) should not be combined.

10. Deleting a File

Rust provides fs::remove_file() to delete a file.

Example:

use std::fs;

fn main() {
fs::remove_file("student.txt")
.expect("Unable to delete file");

println!("File deleted successfully!");
}

The file will be permanently removed from its directory.

Important: The file must exist, otherwise the operation returns an error.

11. Renaming a File

Rust provides fs::rename() to rename a file.

Example:

use std::fs;

fn main() {
fs::rename("student.txt", "student_data.txt")
.expect("Unable to rename file");

println!("File renamed successfully!");
}

Here, student.txt is renamed to student_data.txt.

The exact behaviour when the destination already exists can vary by operating system.

12. Copying a File

Use fs::copy() to copy one file into another.

Example:

use std::fs;

fn main() {
fs::copy("student.txt", "student_backup.txt")
.expect("Unable to copy file");

println!("File copied successfully!");
}

This creates student_backup.txt containing the same data as student.txt.

13. Creating Directories

Rust provides fs::create_dir() to create a directory.

Example:

use std::fs;

fn main() {
fs::create_dir("students")
.expect("Unable to create directory");

println!("Directory created!");
}

This creates a folder named students.

Creating Nested Directories

Use fs::create_dir_all() to create a directory and any missing parent directories.

Example:

use std::fs;

fn main() {
fs::create_dir_all("data/students/records")
.expect("Unable to create directories");

println!("Directories created!");
}

This creates the complete directory structure if it does not already exist.

14. Reading Directory Contents

Rust provides fs::read_dir() to read the entries inside a directory.

Example:

use std::fs;

fn main() {
let entries = fs::read_dir("data")
.expect("Unable to read directory");

for entry in entries {
let entry = entry.expect("Unable to read entry");

println!("{:?}", entry.file_name());
}
}

This displays the names of the entries inside the data directory.

The order of entries is not guaranteed.

15. Checking Whether a File Exists

You can use Path::exists() to check whether a file or directory exists.

Example:

use std::path::Path;

fn main() {
let path = Path::new("student.txt");

if path.exists() {
println!("File exists");
} else {
println!("File does not exist");
}
}

Output if the file exists:

File exists

For more detailed checks, you can use:

path.is_file();
path.is_dir();

These methods check whether the path refers to a file or directory.

16. Getting File Metadata

Metadata provides information about a file.

For example:

  1. File size
  2. Whether it is a file or directory
  3. Last modification time
  4. Permissions

Example:

use std::fs;

fn main() {
let metadata = fs::metadata("student.txt")
.expect("Unable to get metadata");

println!("File Size: {} bytes", metadata.len());
println!("Is File: {}", metadata.is_file());
println!("Is Directory: {}", metadata.is_dir());
}

Example Output:

File Size: 20 bytes
Is File: true
Is Directory: false

The file size depends on the actual contents.

17. Reading Large Files Using BufReader

When reading a large file, loading the entire file into memory may not be efficient.

Rust provides BufReader to read data using a buffer.

Example:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
let file = File::open("student.txt")
.expect("Unable to open file");

let reader = BufReader::new(file);

for line in reader.lines() {
println!("{}", line.expect("Unable to read line"));
}
}

Explanation:

  1. File::open() opens the file.
  2. BufReader::new() creates a buffered reader.
  3. lines() reads the file one line at a time.

This is useful when processing large text files.

18. Writing Large Files Using BufWriter

Rust provides BufWriter to write data through a buffer.

Example:

use std::fs::File;
use std::io::{BufWriter, Write};

fn main() {
let file = File::create("report.txt")
.expect("Unable to create file");

let mut writer = BufWriter::new(file);

for i in 1..=5 {
writeln!(writer, "Student {}", i)
.expect("Unable to write");
}

println!("Report created!");
}

File contents:

Student 1
Student 2
Student 3
Student 4
Student 5

BufWriter reduces the number of direct write operations by buffering data.

When the writer goes out of scope, it attempts to flush the remaining buffered data. For important operations, you can explicitly call flush() and handle its error.

19. Understanding Path and PathBuf

Rust provides two useful types for working with file paths.

Path

Path is used to represent and inspect a file system path.

PathBuf

PathBuf is an owned, mutable path buffer.

Example:

use std::path::PathBuf;

fn main() {
let mut path = PathBuf::from("data");

path.push("students");

path.push("student.txt");

println!("{:?}", path);
}

Output on Windows:

"data\\students\\student.txt"

The path separator depends on the operating system.

20. Understanding File Errors

File operations can fail for many reasons:

  1. File does not exist.
  2. Permission is denied.
  3. Disk is full.
  4. Directory does not exist.
  5. File is already in use.

Rust uses Result<T, E> to handle these errors.

Example:

use std::fs;

fn main() {
match fs::read_to_string("student.txt") {
Ok(content) => {
println!("File Content:");
println!("{}", content);
}

Err(error) => {
println!("Unable to read file: {}", error);
}
}
}

This is safer than using unwrap() or expect() when an error is an expected possibility.

21. Difference Between fs::write() and write_all()


fs::write()

write_all()

Convenience function

Method from the Write trait

Takes a file path and data

Writes to an already-open writer

Creates or replaces a file

Uses the writer's existing opening mode

Suitable for simple file writing

Useful for controlled file operations

22. Common Mistakes


Mistake

Explanation

Using read_to_string() for binary files

It expects valid UTF-8 text

Using File::create() on an existing file

It truncates the existing contents

Forgetting to import Write

Required for methods such as write_all() and macros such as writeln!() on file writers

Opening a missing file with File::open()

Returns an error

Forgetting to handle Result

File operations can fail

Using create_dir() for nested missing directories

Use create_dir_all() when parent directories may be missing

Loading huge files entirely into memory

Consider BufReader and line-by-line processing

23. Practice Exercises

Exercise 1: Create a File

Create a file named hello.txt and write:

Welcome to Rust Programming

Exercise 2: Read a File

Read the contents of hello.txt and display them.

Exercise 3: Append Data

Append the following line:

Learning File Handling

Exercise 4: Copy a File

Copy hello.txt into backup.txt.

Exercise 5: Rename a File

Rename backup.txt to student_backup.txt.

Exercise 6: Delete a File

Delete student_backup.txt.

Exercise 7: Directory Management

Create this directory structure:

data/
students/
records/

24. Mini Project: Student Records File Management

Create a simple application that stores student information in a text file.

Requirements

  1. Create a file named students.txt.
  2. Add student information.
  3. Read and display all records.
  4. Append new student records.
  5. Handle file errors.

Complete Code

use std::fs::OpenOptions;
use std::io::{self, BufRead, BufReader, Write};

fn add_student(name: &str, course: &str) -> io::Result<()> {
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open("students.txt")?;

writeln!(file, "Name: {}, Course: {}", name, course)?;

Ok(())
}

fn show_students() -> io::Result<()> {
let file = std::fs::File::open("students.txt")?;

let reader = BufReader::new(file);

println!("Student Records:");

for line in reader.lines() {
println!("{}", line?);
}

Ok(())
}

fn main() -> io::Result<()> {
add_student("Hemant", "Rust")?;
add_student("Rahul", "Python")?;
add_student("Amit", "Java")?;

show_students()?;

Ok(())
}

Expected Output

Student Records:
Name: Hemant, Course: Rust
Name: Rahul, Course: Python
Name: Amit, Course: Java

Important: Every time you run this program, it appends three more records. It does not clear the previous records.