fs::write, fs::read, fs::read_to_string, fs::metadata, fs::create_dir
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>
pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>>
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>
pub fn metadata<P: AsRef<Path>>(path: P) -> Result<Metadata>
pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<()>Write and read a whole file, then inspect metadata, all inside a temporary directory that the example does not print.
| Parameter | Description |
|---|---|
path | A path, accepted as any AsRef<Path>. The example joins a file name onto a temporary directory from std::env::temp_dir. |
contents | The bytes to write. A string or a byte slice both implement AsRef<[u8]>. |
Returns: write and create_dir return Result<()>. read returns Result<Vec<u8>>. read_to_string returns Result<String>. metadata returns Result<Metadata>.
Errors and panics
io::Error— Returned when the file cannot be created, read, or inspected. Use ErrorKind for portable checks. The missing-file case is shown in the next example.
- The printed byte slice [104, 105] is UTF-8 for "hi". len() is 2 on this host for that file.
- create_dir fails if the directory already exists; create_dir_all creates missing parents and succeeds if the path already exists as a directory.
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let dir: PathBuf = std::env::temp_dir().join(format!("rust-ref-{}-{}", std::process::id(), nanos));
fs::create_dir_all(&dir).unwrap();
let file = dir.join("note.txt");
fs::write(&file, b"hi").unwrap();
let bytes = fs::read(&file).unwrap();
let text = fs::read_to_string(&file).unwrap();
let meta = fs::metadata(&file).unwrap();
println!("read {bytes:?} {text:?} len={}", meta.len());
let sub = dir.join("sub");
fs::create_dir(&sub).unwrap();
println!("dir {}", fs::metadata(&sub).unwrap().is_dir());
fs::remove_dir_all(&dir).unwrap();
}Expected output
read [104, 105] "hi" len=2
dir trueRelated: io Read and Write