XAMPPRocky
XAMPPRocky

Reputation: 3609

How to check if a given path is a file or directory?

I'm building a program that should be able to take both paths to files (*.*), and directories (./, ..). I want to be able to check if the path supplied is a file, or a directory.

Upvotes: 27

Views: 18323

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14621

As of rustc 1.67.1 (d5a82bbd2 2023-02-07) you can use std::path::PathBuf:

let path = PathBuf::from(".");
let is_dir = path.is_dir();
let is_file = path.is_file();
println!("is_dir: {is_dir}");
println!("is_file : {is_file}");

This is the output when you execute the code with a REPL:

Welcome to evcxr. For help, type :help
>> use std::path::PathBuf;
>> let path = PathBuf::from(".");
>> let is_dir = path.is_dir();
>> let is_file = path.is_file();
>> println!("is_dir: {is_dir}");
is_dir: true
>> println!("is_file : {is_file}");
is_file : false

Upvotes: 9

fjh
fjh

Reputation: 13091

You should use std::fs::metadata:

use std::fs::metadata;

fn main() {
    let md = metadata(".").unwrap();
    println!("is dir: {}", md.is_dir());
    println!("is file: {}", md.is_file());
}

Output:

is dir: true
is file: false

Upvotes: 49

Related Questions