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.
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:
Example:
Output:
A file named student.txt will be created in the program's current working directory.
Its contents will be:
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:
Output:
Explanation:
fs::read_to_string()reads the file.- The file contents are returned as a
String. 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:
Updated file contents:
Explanation:
OpenOptions::new()creates file-opening options..append(true)opens the file in append mode..open()opens the existing file.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):
6. Using File::create()
Rust also provides File::create() to create a file.
Example:
File contents:
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:
Output:
Explanation:
File::open()opens an existing file.String::new()creates an empty String.read_to_string()reads the file contents into that String.
8. Difference Between File::create() and File::open()
Method | Purpose |
|---|---|
| Creates a file for writing; truncates an existing file |
| 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:
Common options:
Option | Purpose |
|---|---|
| Allows reading |
| Allows writing |
| Writes at the end of the file |
| Creates the file if it does not exist |
| Removes existing contents when opening for writing |
| 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:
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:
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:
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:
This creates a folder named students.
Creating Nested Directories
Use fs::create_dir_all() to create a directory and any missing parent directories.
Example:
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:
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:
Output if the file exists:
For more detailed checks, you can use:
These methods check whether the path refers to a file or directory.
16. Getting File Metadata
Metadata provides information about a file.
For example:
- File size
- Whether it is a file or directory
- Last modification time
- Permissions
Example:
Example Output:
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:
Explanation:
File::open()opens the file.BufReader::new()creates a buffered reader.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:
File contents:
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:
Output on Windows:
The path separator depends on the operating system.
20. Understanding File Errors
File operations can fail for many reasons:
- File does not exist.
- Permission is denied.
- Disk is full.
- Directory does not exist.
- File is already in use.
Rust uses Result<T, E> to handle these errors.
Example:
This is safer than using unwrap() or expect() when an error is an expected possibility.
21. Difference Between fs::write() and write_all()
|
|
|---|---|
Convenience function | Method from the |
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 | It expects valid UTF-8 text |
Using | It truncates the existing contents |
Forgetting to import | Required for methods such as |
Opening a missing file with | Returns an error |
Forgetting to handle | File operations can fail |
Using | Use |
Loading huge files entirely into memory | Consider |
23. Practice Exercises
Exercise 1: Create a File
Create a file named hello.txt and write:
Exercise 2: Read a File
Read the contents of hello.txt and display them.
Exercise 3: Append Data
Append the following line:
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:
24. Mini Project: Student Records File Management
Create a simple application that stores student information in a text file.
Requirements
- Create a file named
students.txt. - Add student information.
- Read and display all records.
- Append new student records.
- Handle file errors.
Complete Code
Expected Output
Important: Every time you run this program, it appends three more records. It does not clear the previous records.