Reputation: 3609
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
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
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