Rust
Directory operations
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()).
Exercise 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.
Show example 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(())
}
Test yourself
-
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
Show answer
remove_dir only deletes an empty folder; remove_dir_all deletes it with its contents — remove_dir_all can't be undone; double-check the path before using it.
-
List the folder
for giris in fs::____("veri")? {
let giris = giris?;
}
Show answer
for giris in fs::read_dir("veri")? {
let giris = giris?;
}
-
Function and job
- create_dir_all
- Creates with intermediate folders
- read_dir
- Lists entries
- remove_dir_all
- Deletes with contents
- Path::extension
- File extension
Next lesson: Summary - File I/O