find the name of a file in rust

To find the name of a file in Rust, you can use the file_name method of the Path struct from the std::path module. Here is an example:

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

fn main() {
    let path = Path::new("/path/to/file.txt");
    let file_name = path.file_name().unwrap().to_str().unwrap();
    println!("File name: {}", file_name);
}
190 chars
8 lines

In this example, we create a Path instance representing the file /path/to/file.txt. We then call the file_name method to get a Option<&OsStr> containing the file name. The unwrap method is called twice to extract the OsStr value and convert it to a &str containing the file name.

The output of the println statement will be:

main.rs
File name: file.txt
20 chars
2 lines

related categories

gistlibby LogSnag