Probe Path Types With fs metadata
Classify paths with fs::metadata: is_dir and len for existing entries, ErrorKind::NotFound for missing ones, no read of the file content.
Code
use std::fs;
use std::io::ErrorKind;
fn describe(path: &str) -> String {
match fs::metadata(path) {
// 目录的 len 在不同文件系统上不同,只分类不报大小
Ok(meta) if meta.is_dir() => "dir".to_string(),
Ok(meta) => format!("file, {} bytes", meta.len()),
Err(err) if err.kind() == ErrorKind::NotFound => "missing".to_string(),
Err(err) => format!("error: {err}"),
}
}
fn main() {
let path = "probe-me.txt";
fs::write(path, "hello").unwrap();
println!("{path}: {}", describe(path));
fs::create_dir("probe-dir").unwrap();
println!("probe-dir: {}", describe("probe-dir"));
fs::remove_file(path).unwrap();
fs::remove_dir("probe-dir").unwrap();
println!("{path}: {}", describe(path));
}Classification without reading content
describe(path) matches fs::metadata(path): a directory prints dir, a file prints file, N bytes from meta.len(), and ErrorKind::NotFound prints missing — no file content is read at any point.
Three probe targets
The demo writes probe-me.txt (“hello”), creates probe-dir, prints both classifications, then removes both and shows the missing branch. The error arm formats any non-NotFound error with its Display.
Why match on ErrorKind
NotFound is the expected “absent” case; treating every error as fatal would conflate absence with permission or IO failures, which the final error arm keeps distinct.
Interactive Tools for This Topic
FAQ
- Why does describe() only report size for files?
- Directory len is filesystem-dependent and not meaningful for classification, so the demo prints just dir for directories.
- How is a missing path handled?
- By matching err.kind() == ErrorKind::NotFound and printing missing, keeping absence separate from other IO errors.
Report a problem with this exampleOpens a pre-filled issue on GitHub.