Work with Directories
Recipe | Crates | Categories |
---|---|---|
Get the Current Working Directory | ||
remove_dir_all |
Creating, listing, deleting, and recursively traversing directories.
Get the Current Working Directory
use std::env; use anyhow::Result; fn main() -> Result<()> { let cwd = env::current_dir()?; println!("The current directory is {}", cwd.display()); Ok(()) }
remove_dir_all
A safe, reliable implementation of remove_dir_all
⮳ for Windows.
use std::io; // This library provides an alternative implementation of // std::fs::remove_dir_all from the Rust std library. use remove_dir_all::remove_dir_all; fn main() -> io::Result<()> { // Create a directory structure for demonstration (if it doesn't exist // already) std::fs::create_dir_all("temp/example_dir/sub_dir")?; std::fs::write("temp/example_dir/file1.txt", "Hello, world!")?; std::fs::write("temp/example_dir/sub_dir/file2.txt", "Rust is awesome!")?; println!("Directory and files created successfully!"); // Now, remove the directory and all of its contents match remove_dir_all("temp/example_dir") { Ok(_) => println!( "Directory 'example_dir' and all contents removed successfully!" ), Err(e) => eprintln!("Failed to remove directory 'example_dir': {}", e), } Ok(()) }