std::fs::read_to_string() / write()
Rust's std::fs module provides convenience functions — read_to_string(), write(), and read() — that let you read from and write to files in a single line. They are ideal for small files and are typically used together with the ? operator.
Syntax
use std::fs;
// Read the entire file as a String.
let content: String = fs::read_to_string("path/to/file.txt")?;
// Read the entire file as a byte vector (Vec<u8>).
let bytes: Vec<u8> = fs::read("path/to/file.bin")?;
// Write a string to a file (overwrites; creates the file if it does not exist).
fs::write("output.txt", "Hello, Rust!\n")?;
// Write a byte slice to a file.
fs::write("output.bin", &[0u8, 1, 2, 3])?;
// Copy a file.
fs::copy("src.txt", "dst.txt")?;
// Delete a file.
fs::remove_file("file.txt")?;
// Create a directory, including any missing parent directories.
fs::create_dir_all("path/to/dir")?;
Function Reference
| Function | Description |
|---|---|
| fs::read_to_string(path) | Reads the entire file as a UTF-8 string. Returns Result<String>. |
| fs::read(path) | Reads the entire file as a byte vector. Returns Result<Vec<u8>>. |
| fs::write(path, data) | Writes data to a file, overwriting any existing content. Returns Result<()>. |
| fs::copy(from, to) | Copies a file. Returns the number of bytes copied. |
| fs::rename(from, to) | Moves or renames a file. |
| fs::remove_file(path) | Deletes a file. |
| fs::remove_dir(path) | Deletes an empty directory. |
| fs::remove_dir_all(path) | Deletes a directory and all of its contents. |
| fs::create_dir(path) | Creates a single directory. |
| fs::create_dir_all(path) | Recursively creates a directory and all missing parent directories. |
| fs::metadata(path) | Retrieves file metadata such as size and last-modified time. |
Sample Code
use std::fs;
use std::io;
fn main() -> io::Result<()> {
// Write to a file.
fs::write("hello.txt", "Hello, Rust!\nFile write test.\n")?;
println!("Wrote to hello.txt");
// Read the file.
let content = fs::read_to_string("hello.txt")?;
println!("Contents:\n{}", content);
// Read the file as bytes.
let bytes = fs::read("hello.txt")?;
println!("File size: {} bytes", bytes.len());
// Copy the file.
fs::copy("hello.txt", "hello_copy.txt")?;
println!("Copied to hello_copy.txt");
// Retrieve metadata.
let meta = fs::metadata("hello.txt")?;
println!("Size: {} bytes", meta.len());
println!("Read-only: {}", meta.permissions().readonly());
// Create a nested directory.
fs::create_dir_all("test/nested/dir")?;
println!("Directory created");
// Write a file inside the nested directory.
fs::write("test/nested/dir/data.txt", "Nested file")?;
// Clean up.
fs::remove_file("hello_copy.txt")?;
fs::remove_dir_all("test")?;
fs::remove_file("hello.txt")?;
println!("Cleanup complete");
Ok(())
}
Notes
fs::read_to_string() and fs::write() are the best choice for reading and writing small files. Both return a Result, so you can propagate errors to the caller with the ? operator.
For large files or line-by-line processing, use File::open() with BufReader for better efficiency. See File::open() / File::create() for details.
Note: fs::write() overwrites an existing file. To append instead, use OpenOptions::new().append(true). For file path manipulation, see std::path::Path / PathBuf.
If you find any errors or copyright issues, please contact us.