Directory operations
- Rust course
- Intermediate
- Lesson 93/115
- 4 min
List directory contents with read_dir.
Directory operations
The std::fs functions are used to create, list and delete folders. read_dir returns an iterator where each item is an io::Result<DirEntry>:
fs::create_dir_all("veri/2024")?; // also creates intermediate folders
for giris in fs::read_dir("veri")? {
let giris = giris?;
println!("{:?} {}", giris.file_name(), giris.path().is_dir());
}read_dir doesn't yield entries in any particular order; if you need an order, collect the names and sort them.
Filtering by extension
Path methods split paths without string processing:
let yol = std::path::Path::new("veri/rapor.txt");
println!("{:?}", yol.file_name()); // Some("rapor.txt")
println!("{:?}", yol.extension()); // Some("txt")
println!("{:?}", yol.parent()); // Some("veri")
println!("{}", yol.exists());extension() returns an Option<&OsStr>; to compare, use == Some(OsStr::new("txt")) or .and_then(|e| e.to_str()).
Practice Folder contents
Create a folder named rust_ders_klasor in the temp folder (create_dir_all) and write b.txt and a.txt into it. Collect the file names into a Vec<String> with read_dir, sort and print them.
Starter code
use std::env;
use std::fs;
use std::io;
fn main() {
// buraya yaz
}Sample solution
use std::env;
use std::fs;
use std::io;
fn main() -> io::Result<()> {
let klasor = env::temp_dir().join("rust_ders_klasor");
fs::create_dir_all(&klasor)?;
fs::write(klasor.join("b.txt"), "2")?;
fs::write(klasor.join("a.txt"), "1")?;
let mut adlar = Vec::new();
for giris in fs::read_dir(&klasor)? {
let giris = giris?;
adlar.push(giris.file_name().to_string_lossy().into_owned());
}
adlar.sort();
println!("{:?}", adlar);
Ok(())
}Expected output
["a.txt", "b.txt"]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between <code>fs::remove_dir</code> and <code>fs::remove_dir_all</code>?
- No difference
- remove_dir_all moves to the recycle bin
- remove_dir deletes files
- remove_dir only deletes an empty folder; remove_dir_all deletes it with its contents Correct answer
Explanation: remove_dir_all can't be undone; double-check the path before using it.
2 List the folder
for giris in fs::____("veri")? {
let giris = giris?;
}
for giris in fs::read_dir("veri")? {
let giris = giris?;
}
Explanation: read_dir yields the folder's entries as DirEntry.
3 Function and job
| Term | Meaning |
|---|---|
create_dir_all |
Creates with intermediate folders |
read_dir |
Lists entries |
remove_dir_all |
Deletes with contents |
Path::extension |
File extension |