How to List Files of a Directory in Rust

Created
Modified

Using read_dir Function

The fs::read_dir() function returns an iterator over the entries within a directory.

See the following example:

use std::fs;

fn main() {
  let paths = fs::read_dir("./").unwrap();

  for path in paths {
    println!("{}", path.unwrap().path().display())
  }
}
./.gitignore
./Cargo.toml
./src
./file.txt

Rust Errors

This function will return an error in the following situations, but is not limited to just these cases:

  • The provided path doesn’t exist.
  • The process lacks permissions to view the contents.
  • The path points at a non-directory file.
let paths = fs::read_dir("./a").unwrap();
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:4:35
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Related Tags