For processing large amounts of files in Rust, we need a function that gets the name of each file in a directory. The fs::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.
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()
.
read_dir
) we must handle errors, and io::Result
is how we do this.read_dir()
call returns ReadDir
structs, and we must use a question mark to indicate it may cause an error.path()
to get the file name string
from each ReadDir
struct
. We use unwrap
to get the inner string
from the Option
.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
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.
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.