read_dir: Get Files From Directory
This page was last reviewed on Jun 25, 2021.
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().
Info When we use a function that accesses the disk (like read_dir) we must handle errors, and "io::Result" I show we do this.
Detail When we handle errors, we must signal that a function has returned correctly and not caused an error—Ok() is used for this purpose.
Detail This returns the ReadDir structs, and we must use a question mark to indicate it may cause an error.
Detail We call path() to get the file name string from each ReadDir struct. We use unwrap to get the inner string from the Option.
use std::{fs, io}; fn main() -> io::Result<()> { // Get all files in target directory. // Replace "." with a more useful directory if needed. for entry in fs::read_dir(".")? { let path = entry?.path(); // Get path string. let path_str = path.to_str().unwrap(); println!("PATH: {}", path_str); } 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.
A 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 Jun 25, 2021 (new).
© 2007-2024 Sam Allen.