CHAPTER 20
Beginner
File Handling in Rust
Updated: May 18, 2026
5 min read
# CHAPTER 20
File Handling in Rust
1. Chapter Introduction
Any robust application, whether a database engine or a simple CLI, needs to persist data. In this chapter, we will learn how to interact with the file system using Rust's standard library (std::fs). We will combine our knowledge of String manipulation and the Result enum to read, write, and append data safely.
2. Learning Objectives
By the end of this chapter, you will be able to:- Read the entire contents of a file into a String.
- Write new data to a file (overwriting existing content).
- Append data to an existing file.
-
Understand the
std::fsandstd::iomodules.
3. Reading a File
The easiest way to read a file in Rust is to use thefs::read_to_string function. It opens the file, reads all the UTF-8 text into a String, and closes the file automatically.
rust
4. Writing to a File
To write data, we can usefs::write.
*Warning: If the file exists, this will completely overwrite it! If it does not exist, it will create it.*
rust
5. Appending to a File
If you are building a log file, you don't want to overwrite the data every time; you want to *append* to the end. For this, we need more control. We useOpenOptions.
rust
6. Mini Project: Notes Manager
Let's build a small application that asks the user for a note and saves it permanently to anotes.txt file using the ? error propagation operator we learned in Chapter 15.
rust
7. Common Mistakes
-
Forgetting
use std::io::Write;: If you try to use.write_all(), the compiler will complain that the method doesn't exist unless you bring theWritetrait into scope!
-
Pathing Issues: Expecting
"file.txt"to be relative to the.rsfile. It is actually relative to where you executecargo run(usually the root directory of the project).
8. Best Practices
-
Never use
unwrap()for File I/O: File operations are the most likely things to fail in a program (due to permissions, missing files, or full hard drives). Always handle theResult.
9. Exercises
-
1.
Write a program that uses
fs::writeto create a file namedsecret.txtcontaining the word "Rust".
-
2.
Use
fs::read_to_stringto readsecret.txtand print the contents to the console.
10. MCQs with Answers
Question 1
Which standard library module handles file system operations?
Question 2
What is the simplest function to read an entire file into a String?
Question 3
If fs::read_to_string fails (e.g., file not found), what does it return?
Question 4
What happens if you use fs::write() on a file that already exists?
Question 5
To append data to an existing file, which struct must you use to configure the file opening?
Question 6
What trait must be brought into scope (use std::io::Write;) to use the .write_all() method?
Question 7
When you pass a string to .write_all(), what format must it be in?
Question 8
Why is it dangerous to use .unwrap() on file operations in a production app?
Question 9
What does the b prefix mean in b"Hello"?
Question 10
Where does cargo run expect "notes.txt" to be located by default?
11. Interview Questions
-
Q: Explain how Rust handles the closing of file handles. Do you need to call
file.close()? (Answer: No, Rust's Ownership rules automatically drop the file handle and close the OS resource when thefilevariable goes out of scope).
12. Summary
File handling in Rust is designed around explicit error handling. Thestd::fs module provides rapid functions for simple tasks, while OpenOptions grants granular control for logging and appending. Coupled with Rust's automatic memory management dropping the file handle safely, your I/O code is both expressive and leak-free.