File input/output operations are essential for working with data stored in files. In Rust, reading and writing files involves utilizing the std::fs::File
struct and other related types. This Answer provides a step-by-step approach to reading and writing files, error handling, and working with file metadata.
For reading a file in Rust, the following syntax is typically used:
let file = File::open(path)?;let reader = BufReader::new(file);for line in reader.lines() {println!("{}", line?);}
For creating a new file and writing to it, the following syntax is typically used in Rust:
let mut file = File::create(path)?;write!(file, "Hello World!")?;
For writing to an existing file, the following syntax is typically used in Rust:
let mut file = OpenOptions::new().append(true).open("example.txt").expect("Unable to open file");file.write_all("Hello World!\n".as_bytes()).expect("write failed");
Let's see a complete example of creating, reading, and writing files in Rust:
//Necessary importsuse std::fs::File;use std::fs::OpenOptions;use std::io::{Write, BufReader, BufRead, Error};fn main() -> Result<(), Error> {let path = "output/example.txt";// creatinglet mut open = File::create(path)?;// writing to filewrite!(open, "Hello World!\n")?;// readingprintln!("{}", "First read:");let open = File::open(path)?;let reader = BufReader::new(open);for x in reader.lines() {println!("{}", x?);}// writing to an existing filelet mut open = OpenOptions::new().append(true).open(path).expect("Unable to open file");open.write_all("Again Hello World!\n".as_bytes()).expect("write failed");// readingprintln!("{}", "Second read:");let open = File::open(path)?;let reader = BufReader::new(open);for x in reader.lines() {println!("{}", x?);}Ok(())}
Note: To view the output of the code above, press the arrow at the right.
The code above is explained in detail below:
Lines 2–4: We import the necessary modules and types from the standard library.
Line 7: We initialize the path
variable with the path of the file.
Line 9: The File::create(path)?
creates a new file at the specified path and returns a File
object. The ?
operator is used to propagate any potential error that occurs during file creation.
Line 11: We use the write()
function to write into our file.
Lines 15–20: We read the newly created file.
Lines 22–23: Here, we update the file using OpenOptions::new().append(true).open(path)
that opens the file in the append mode and returns a mutable File
object.
Lines 26–31: We read the file again.
Reading and writing files in Rust is a fundamental aspect of file I/O operations. We can perform efficient and reliable file operations by utilizing the struct, along with other related types and functions.
Free Resources