Rust Recipes is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.

Question: How to get a vector (Vec<String>) containing all filenames of a particular directory in Rust?

We can use the fs and io modules from the Rust standard library to solve this task.

RUST
use std::{fs, io};

fn get_files_in_directory(path: &str) -> io::Result<Vec<String>> {
    // Get a list of all entries in the folder
    let entries = fs::read_dir(path)?;

    // Extract the filenames from the directory entries and store them in a vector
    let file_names: Vec<String> = entries
        .filter_map(|entry| {
            let path = entry.ok()?.path();
            if path.is_file() {
                path.file_name()?.to_str().map(|s| s.to_owned())
            } else {
                None
            }
        })
        .collect();

    Ok(file_names)
}

In this example, we pass the path of the desired directory as an argument to the get_files_in_directory function. We then use the fs::read_dir() function to get a list of all entries in the directory, which returns a std::fs::ReadDir iterator. Every item of that iterator is an io::Result<DirEntry>. We use the filter_map() method together with ok()? to skip entries that could not be read, then check whether each entry is a file using the is_file() method of the std::path::Path struct. Note that is_file() follows symbolic links, so a symlink pointing to a file is also considered a file.

If the entry is a file, we extract the filename using the file_name() method and convert it to a String using the to_str() and to_owned() methods. If the entry is not a file, we return None to filter it out of the iterator. Finally, we use the collect() method to collect the filenames into a Vec<String>. Keep in mind that read_dir does not guarantee any particular order, so we should sort the result if we need a stable order.

We can call the get_files_in_directory function as shown here:

RUST
fn main() {
    match get_files_in_directory("/tmp") {
        Ok(file_names) => {
            for file_name in file_names {
                println!("{file_name}");
            }
        }
        Err(e) => println!("Error: {e}"),
    }
}

Community Feedback

As suggested by Thomas Darimont here , it may be more convenient to return a Vector of std::path::PathBuf, which allows further processing for every item. See the following implementation of get_files_in_folder returning a Vec<PathBuf>. It allows the caller to do things like:

  • check if PathBuf is a directory or a file
  • check if PathBuf is a symlink
  • do even more complex examinations by consulting PathBuf::metadata()
RUST
use std::{fs, io, path::PathBuf};

fn get_files_in_folder(path: &str) -> io::Result<Vec<PathBuf>> {
    let entries = fs::read_dir(path)?;
    let all: Vec<PathBuf> = entries
        .filter_map(|entry| Some(entry.ok()?.path()))
        .collect();
    Ok(all)
}

The alternative implementation can be used like this. We check for symlinks first because is_dir() and metadata() follow symbolic links:

RUST
fn main() {
    match get_files_in_folder("/tmp") {
        Ok(files) => {
            for file in files {
                if file.is_symlink() {
                    println!("{} is a symlink", file.display());
                    continue;
                }
                if file.is_dir() {
                    println!("{} is a directory", file.display());
                    continue;
                }

                let Ok(m) = file.metadata() else {
                    println!("Could not get metadata for {}", file.display());
                    continue;
                };

                if m.len() == 0 {
                    println!("{} is an empty file", file.display());
                    continue;
                }
                println!("{} is a file", file.display());
            }
        }
        Err(e) => println!("Error: {e}"),
    }
}

Want to continue working with files in Rust? Check out how to compute a SHA256 hash of a file , how to download an image to a file , or how to read a CSV file .