Home
Rust
read_dir: Get Files From Directory
This page was last reviewed on Dec 4, 2024.
Dot Net Perls
Read dir. For processing large amounts of files in Rust, we need a function that gets the name of each file in a directory. The read_dir function is helpful here.
With this function, we can loop over the names of files in a directory. Then, on each ReadDir struct, we can access the path() function.
Example code. To begin, we must include the fs and io modules from "std" at the top of the program. Notice how we must return an "io::Result" from main().
Part 1 When we use a function that accesses the disk (like read_dir) we must handle errors, and "io::Result" is how we do this.
Part 2 The read_dir() call returns ReadDir structs, and we must use a question mark to indicate it may cause an error.
Part 3 We call path() to get the file name string from each ReadDir struct. We use unwrap to get the inner string from the Option.
Part 4 When we handle errors, we must signal that a function has returned correctly and not caused an error—Ok() is used for this purpose.
use std::{fs, io}; // Part 1: Return io::Result. fn main() -> io::Result<()> { // Part 2: Get all files in target directory. // ... Replace "." with a more useful directory if needed. for entry in fs::read_dir(".")? { // Part 3: get path and path str. let path = entry?.path(); let path_str = path.to_str().unwrap(); println!("PATH: {}", path_str); } // Part 4: return Ok. Ok(()) }
PATH: ./Cargo.toml PATH: ./target PATH: ./Cargo.lock PATH: ./_profile PATH: ./.gitignore PATH: ./.git PATH: ./src
Some notes. File handling in Rust involves many concepts, including io::Result and the Ok() function to signal correct operation. Most of these concepts become familiar with practice.
Summary. We looped overall the file names in a directory. And we printed out the string representations of each path. The code involved many concepts from IO in Rust.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 4, 2024 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.