File Operations in Rust: Creating, Writing, Reading, and Deleting Files
Table of contents
No headings in the article.
In Rust, file operations can be performed using the standard library's std::fs
module. The module provides functions for creating, writing, reading, and deleting files.
To create a file in Rust, we can use the File::create
method. Here's an example:
use std::fs::File;
let mut file = File::create("file.txt").expect("Unable to create file");
In this example, we create a new file called file.txt
. If the file already exists, it will be truncated to zero length.
To write data to a file, we can use the write_all
method provided by the std::io::Write
trait. Here's an example:
use std::io::prelude::*;
let mut file = File::create("file.txt").expect("Unable to create file");
file.write_all(b"Hello, world!").expect("Unable to write data to file");
In this example, we write the string "Hello, world!" to the file.txt
file.
To open an existing file for writing, we can use the OpenOptions
struct. Here's an example:
use std::fs::OpenOptions;
let mut file = OpenOptions::new()
.write(true)
.open("file.txt")
.expect("Unable to open file");
In this example, we open the file.txt
file for writing and set the write
flag to true
.
To read data from a file, we can use the File::open
method to open the file, and then use a BufReader
to read the file line by line. Here's an example:
use std::fs::File;
use std::io::{BufReader, prelude::*};
let file = File::open("file.txt").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
println!("{}", line.unwrap());
}
In this example, we read the file.txt
file line by line using a BufReader
, and then print each line to the console.
Finally, when we're done with a file, we can use the std::fs::remove_file
function to delete it from the system. Here's an example:
use std::fs;
fs::remove_file("file.txt").expect("Unable to delete file");
In this example, we delete the file.txt
file. If there's an error while deleting the file, an error message will be printed.
We can also create a command-line interface (CLI) application that performs file operations. Here's an example:
use std::fs::OpenOptions;
use std::io::{self, Write};
fn main() {
println!("Enter some text:");
let mut text = String::new();
io::stdin()
.read_line(&mut text)
.expect("Failed to read line");
let mut file = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open("example.txt")
.expect("Failed to open file");
writeln!(file, "{}", text).expect("Failed to write to file");
}
In this example, we prompt the user to enter some text, read the text from the standard input, and then append the text to a file called example.txt
. The OpenOptions
struct is used to open the file for writing and to create the file if it doesn't exist. If there's an error while opening or writing to the file,