check if file exists in rust

To check if a file exists in Rust, we can use the std::fs::metadata() function. This function returns a Result object which can be used to determine if the file exists or not. Here's an example:

main.rs
use std::fs;

fn main() {
    let file_path = "path/to/file.txt";

    match fs::metadata(file_path) {
        Ok(_) => println!("File exists!"),
        Err(_) => println!("File not found!"),
    }
}
201 chars
11 lines

In this example, we first define the file_path variable which contains the path to the file we want to check. We then call fs::metadata() with that path, which returns a Result object.

If fs::metadata() returns an Ok variant, that means the file exists. We print "File exists!" in that case. If fs::metadata() returns an Err variant, that means the file does not exist. We print "File not found!" in that case.

We could also use the .is_ok() method to simplify the code:

main.rs
use std::fs;

fn main() {
    let file_path = "path/to/file.txt";

    if fs::metadata(file_path).is_ok() {
        println!("File exists!");
    } else {
        println!("File not found!");
    }
}
200 chars
12 lines

Finally, it's worth noting that the metadata() function returns more information than just whether the file exists, so if we need more information about the file itself we can use this function's return value to extract it.

gistlibby LogSnag