Rust program to check a specified directory exists or not

Rust | File I/O Example: Write a program to check a specified directory exists or not.
Submitted by Nidhi, on November 01, 2021

Problem Solution:

In this program, we will check a specified directory is exists or not using the is_dir() method and print the appropriate message.

Program/Source Code:

The source code to check a specified directory exists or not is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to check a specified directory 
// exists or not

use std::path::Path;

fn main() {
    let path1 = "MyDir";
    let path2 = "MyDir1";
    
    let result1: bool = Path::new(path1).is_dir();
    let result2: bool = Path::new(path2).is_dir();
    
    if result1==true
    {
        println!("Directory 'MyDir' exists");
    }
    else
    {
        println!("Directory 'MyDir' does not exists");
    }
    
    if result2==true
    {
        println!("Directory 'MyDir1' exists");
    }
    else
    {
        println!("Directory 'MyDir1' does not exists");
    }
}

Output:

$ rustc main.rs

$ ./main
Directory 'MyDir' exists
Directory 'MyDir1' does not exists

Explanation:

Here, we checked a specified directory exists or not using the is_dir() method and printed the appropriate message.

Rust File I/O Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.