File Handling in Rust
Rust provides a robust and safe way to handle files using the std::fs
module.
Reading a File
Use the std::fs::read_to_string
function to read the contents of a file into a string.
use std::fs;
fn main() {
let content = fs::read_to_string("example.txt").expect("Failed to read file");
println!("File content: {}", content);
}
Writing to a File
Use the std::fs::write
function to write data to a file.
use std::fs;
fn main() {
fs::write("example.txt", "Hello, Rust!").expect("Failed to write file");
}
Appending to a File
Use the std::fs::OpenOptions
struct to append data to a file.
use std::fs::OpenOptions;
use std::io::Write;
fn main() {
let mut file = OpenOptions::new()
.append(true)
.open("example.txt")
.expect("Failed to open file");
file.write_all("Appending this line!".as_bytes()).expect("Failed to write to file");
}
File Metadata
Retrieve file metadata using the std::fs::metadata
function.
use std::fs;
fn main() {
let metadata = fs::metadata("example.txt").expect("Failed to read metadata");
println!("File size: {} bytes", metadata.len());
println!("Is directory: {}", metadata.is_dir());
}
Error Handling
Handle file-related errors gracefully using the Result
type.
use std::fs;
fn main() {
let result = fs::read_to_string("nonexistent.txt");
match result {
Ok(content) => println!("File content: {}", content),
Err(error) => println!("Error reading file: {}", error),
}
}
Reading and Writing Binary Files
Use std::fs::read
and std::fs::write
for binary file operations.
use std::fs;
fn main() {
// Writing binary data
let data = vec![0, 1, 2, 3, 4];
fs::write("binary.bin", &data).expect("Failed to write binary file");
// Reading binary data
let content = fs::read("binary.bin").expect("Failed to read binary file");
println!("Binary content: {:?}", content);
}
Directory Operations
Create, read, and delete directories using the std::fs
module.
use std::fs;
fn main() {
// Create a directory
fs::create_dir("example_dir").expect("Failed to create directory");
// Read directory contents
let entries = fs::read_dir("example_dir").expect("Failed to read directory");
for entry in entries {
let entry = entry.expect("Failed to read entry");
println!("Entry: {:?}", entry.path());
}
// Delete a directory
fs::remove_dir("example_dir").expect("Failed to delete directory");
}
Interactive Code Examples
Try running these examples in your Rust environment to see how they work!
// Interactive Example
use std::fs;
fn main() {
let content = fs::read_to_string("example.txt").expect("Failed to read file");
println!("File content: {}", content);
}
Practice Problems
Test your understanding with these practice problems:
- Write a Rust program to count the number of lines in a file.
- Write a Rust program to copy the contents of one file to another.
- Write a Rust program to list all files in a directory and its subdirectories.