Last active
May 17, 2025 14:54
-
-
Save clemensg/ab0d94ec2400d8a1c98451f6b2515b90 to your computer and use it in GitHub Desktop.
Rust tree example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{env,ffi,fs,io,path}; | |
const DEFAULT_DEPTH: usize = 1024; | |
fn main() -> io::Result<()> { | |
let max_depth: usize = env::args() | |
.nth(1) | |
.and_then(|s| s.parse().ok()) | |
.unwrap_or(DEFAULT_DEPTH); | |
println!("Directory tree. Max depth = {}", max_depth); | |
// Stack with PathBuf and depth | |
let mut stack: Vec<(path::PathBuf, usize)> = vec![(path::PathBuf::from("."), 0)]; | |
while let Some((path, depth)) = stack.pop() { | |
let name = path.file_name() | |
.unwrap_or(ffi::OsStr::new(".")) // Root path has no file name? | |
.to_string_lossy(); | |
print!("{}{}", " ".repeat(depth), name); | |
if path.is_dir() { | |
println!("/"); | |
if depth < max_depth { | |
for entry in fs::read_dir(&path)? { | |
let child = entry?.path(); | |
stack.push((child, depth + 1)); | |
} | |
} | |
} else { | |
println!() | |
} | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment