File I/O (Input/Output) in Rust allows developers to read from and write to files efficiently. This is crucial for applications that need to store data persistently or read configuration settings. Rust’s standard library provides a powerful and flexible way to handle files, ensuring safety and performance. Below are three diverse examples to demonstrate File I/O in Rust.
Reading from a file is a common task in many applications, such as reading configuration files or input data. This example shows how to read a text file line by line and print its contents.
In this use case, we might want to read a configuration file that contains various settings for our application.
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() -> io::Result<()> {
let path = Path::new("config.txt");
let file = File::open(&path)?;
let reader = io::BufReader::new(file);
for line in reader.lines() {
let line = line?;
println!("{}", line);
}
Ok(())
}
In this example, we use File::open
to open the file and BufReader
to read it line by line. Each line is printed to the console.
Result
to avoid panics.Writing to a file is essential when you want to save data generated by your application. This example demonstrates how to create a new file and write some text into it.
A common use case is logging application events to a file for future reference.
use std::fs::File;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = File::create("output.txt")?;
file.write_all(b"Logging application events!")?;
println!("Data written to output.txt");
Ok(())
}
This example uses File::create
to create a new file called output.txt
. The write_all
method writes the specified byte string to the file.
output.txt
already exists, it will be overwritten.Appending data to an existing file is useful when you want to add new information without losing the previous content. This example illustrates how to append text to a file.
This could be applicable in scenarios where you want to maintain a log file with ongoing events.
use std::fs::OpenOptions;
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open("log.txt")?;
file.write_all(b"New event logged!
")?;
println!("Data appended to log.txt");
Ok(())
}
In this example, we use OpenOptions
to open log.txt
in append mode. The new log entry is then added to the end of the file.
OpenOptions
for more customization.By exploring these examples of File I/O in Rust, you can gain a better understanding of handling file operations effectively in your applications.