#348 Rust File Handling
Reviewing common file operations with rust
Notes
Create
Create a file with std::fs::File::create
- Opens a file in write-only mode.
- Create a file if it does not exist, truncates it if it does.
- Alternatives:
create_buffered
Opens a file in write-only mode with bufferingcreate_new
Creates a new file in read-write mode; error if the file exists.
Example:
use std::fs::File
let mut file = File::create("name.txt").expect("failed");
Or using the ? operator:
let mut file = File::create("name.txt")?;
Write
Write to a file with write_all
- Attempts to write an entire buffer into this writer.
Example:
use std::io::Write;
file.write_all("Hello".as_bytes()).expect("failed");
// or
file.write_all("Hello".as_bytes())?;
Open for Append
Open a file for append using OpenOptions
- A builder used to configure how a File is opened and what operations are permitted on the open file.
- The
File::open
andFile::create
methods are aliases for commonly used options using this builder.
Example:
use std::fs::OpenOptions;
let mut file = OpenOptions::new().append(true).open("name.txt").expect("failed");
file.write_all(" world!\n".as_bytes()).expect("failed");
// or
let mut file = OpenOptions::new().append(true).open("name.txt")?;
file.write_all(" world!\n".as_bytes())?;
Read File
Read from a file with read_to_string
Example:
use std::io::Read;
let mut file = std::fs::File::open("name.txt").unwrap();
file.read_to_string(&mut contents).unwrap();
// or
let mut file = std::fs::File::open("name.txt")?;
file.read_to_string(&mut contents)?;
Delete File
Delete a file with remove_file
use std::fs;
fs::remove_file("name.txt").expect("failed");
// or
fs::remove_file("name.txt")?;
Example Code
use std::fs;
use std::io::{Write, Read};
fn create_file(filename: &str, content: &str) -> std::io::Result<()> {
println!("# creating file: {}", filename);
let mut file = fs::File::create(filename)?;
file.write_all(content.as_bytes())?;
Ok(())
}
fn append_to_file(filename: &str, content: &str) -> std::io::Result<()> {
println!("# appending to file: {}", filename);
let mut file = fs::OpenOptions::new().append(true).open(filename)?;
file.write_all(content.as_bytes())?;
Ok(())
}
fn read_file(filename: &str) -> std::io::Result<String> {
println!("# reading from file: {}", filename);
let mut file = fs::File::open(filename)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn delete_file(filename: &str) -> std::io::Result<()> {
println!("# deleting file: {}", filename);
fs::remove_file(filename)?;
Ok(())
}
fn main() -> std::io::Result<()> {
let filename = "example.txt";
create_file(&filename, "Hello World!\n")?;
println!("{}", read_file(&filename)?);
append_to_file(&filename, "Appended content to the file.\n")?;
println!("{}", read_file(&filename)?);
delete_file(&filename)?;
Ok(())
}
Run:
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/file-demo`
# creating file: example.txt
# reading from file: example.txt
Hello World!
# appending to file: example.txt
# reading from file: example.txt
Hello World!
Appended content to the file.
# deleting file: example.txt