Here is an example that shows some info for all files in the current directory:
// code from Chapter 11/code/read_files_in_dir.rs: use std::env; use std::fs; use std::error::Error; fn main() { show_dir().unwrap(); } fn show_dir() -> Result<(), Box<Error>> { let here = try!(env::current_dir()); println!("Contents in: {}", here.display()); for entry in try!(fs::read_dir(&here)) { let path = try!(entry).path(); let md = try!(fs::metadata(&path)); println!(" {} ({} bytes)", path.display(), md.len()); } Ok(()) }
This prints out:
Contents in: F:\Rust\Rust book\The Rust Programming Language\Chapter 11 - Working with files\code F:\Rust\Rust book\The Rust Programming Language\Chapter 11 - Working with files\code\read_file.rs (710 bytes) F:\Rust\Rust book\The Rust Programming Language\Chapter 11 - Working with files\code\read_files_in_dir.exe (2382143 bytes)
Here are some remarks to clarify the code:
- This code uses the current_dir method from std::env, reads that folder with read_dir, and iterates over all files it contains with for entry in
- To manipulate the filesystem, see filesystem.rs in the code download for examples, which demonstrates the use of the methods create_dir, create_dir_all, remove_file, remove_dir, and read_dir
- The kind() method is used here in the error case, to display the specific I/O error category (from the std::io::ErrorKind enum)
- The fs::read_dir method is used to read the contents of a directory, returning an io::Result<Vec<Path>> paths, which can be looped through with this code:
for path in paths { println!("> {:?}", path.unwrap().path()); }