find the parent directory of a file in rust

To find the parent directory of a file in Rust, we can use the parent method of the Path type from the std::path module:

main.rs
use std::path::Path;

fn main() {
    let path = Path::new("/path/to/file.txt");
    if let Some(parent) = path.parent() {
        println!("{}", parent.display());
    }
}
173 chars
9 lines

In this example, we create a Path object representing the file /path/to/file.txt. The parent method returns an Option<Path> representing the parent directory of the file, or None if the file has no parent directory (e.g., if it is a root directory). We use a match expression to check if the result is Some(parent), and if so, we print the path with the display method.

This will output:

main.rs
/path/to
9 chars
2 lines

Note that the Path type is a lightweight handle to a file system path. It does not actually access the file system.

gistlibby LogSnag