fs

std::fs read and write helpers in a temporary directory, plus copy, rename, and ErrorKind checks that do not depend on OS error text.

The fs module provides functions and types for file-system operations. Import it as std::fs. It is complementary to the io page, which documents the Read and Write traits rather than paths on disk.

The examples create a unique directory under std::env::temp_dir, operate only inside it, and remove it afterward. They never print that path and they do not read a user file, a home directory, or environment values beyond the temporary-directory location. Failed calls return std::io::Result. Compare err.kind() with io::ErrorKind, for example NotFound, instead of matching the Display text of an OS error; that text is not used as an expected output here.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
fs::write, fs::read, fs::read_to_string, fs::metadata, fs::create_dirWrite and read a whole file, then inspect metadata, all inside a temporary directory that the example does not print.
fs::read, fs::copy, fs::rename, fs::remove_file, io::Error::kindDetect a missing file with ErrorKind::NotFound, then copy, rename, and remove files without relying on OS error strings.

write, read, and metadata

fs::write creates or replaces a file and writes the whole contents. fs::read returns the bytes. fs::read_to_string returns a String and fails with ErrorKind::InvalidData when the file is not valid UTF-8. metadata returns a Metadata value; len() is the size in bytes, and is_dir() distinguishes directories. These functions take any AsRef<Path>, so a PathBuf or a string works as the path argument.

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.

ParameterDescription
pathA path, accepted as any AsRef<Path>. The example joins a file name onto a temporary directory from std::env::temp_dir.
contentsThe 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.
rust
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 true

Related: io Read and Write

Official documentation →

ErrorKind, copy, rename, and remove

A missing path from fs::read is an Err whose kind is ErrorKind::NotFound on this host. That enum comparison is the portable check. The Display text of an operating-system error is intentionally not printed or asserted here.

copy copies the contents of one file to another and returns the number of bytes copied. rename renames or moves a file, and the original path no longer exists when it succeeds. remove_file deletes a file. All of these return io::Result.

fs::read, fs::copy, fs::rename, fs::remove_file, io::Error::kind

pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>>
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64>
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()>
pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()>
pub fn kind(&self) -> ErrorKind

Detect a missing file with ErrorKind::NotFound, then copy, rename, and remove files without relying on OS error strings.

ParameterDescription
from / to / pathFilesystem paths inside the temporary directory created by the example.

Returns: copy returns the number of bytes copied as u64. rename and remove_file return Result<()>. kind returns an ErrorKind discriminant such as NotFound.

Errors and panics

  • ErrorKind::NotFound — Observed for fs::read of a path that does not exist in the temporary directory. Do not assert the OS Display text of that error.
  • io::Error — Also returned when a copy, rename, or remove fails, for example if the source is missing or a permission check fails. Permission failures are not forced in this example.
  • exists() is used only to show the outcome of rename and remove. It is not a substitute for handling a Result when you are about to open a file.
rust
use std::fs;
use std::io::ErrorKind;
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");
    let err = fs::read(&file).unwrap_err();
    println!("missing kind={:?}", err.kind());
    println!("missing is_not_found={}", err.kind() == ErrorKind::NotFound);

    fs::write(&file, b"hi").unwrap();
    let dest = dir.join("copy.txt");
    let n = fs::copy(&file, &dest).unwrap();
    println!("copy-bytes {n}");
    let renamed = dir.join("renamed.txt");
    fs::rename(&dest, &renamed).unwrap();
    println!("renamed-exists {} copy-exists {}", renamed.exists(), dest.exists());
    fs::remove_file(&renamed).unwrap();
    println!("after-remove {}", renamed.exists());
    fs::remove_dir_all(&dir).unwrap();
}

Expected output

missing kind=NotFound
missing is_not_found=true
copy-bytes 2
renamed-exists true copy-exists false
after-remove false

Official documentation →