×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to check a given filename is a directory or not

Here, we are going to learn how to check whether a given filename is a directory or not using C program?
By Nidhi Last updated : March 10, 2024

Problem statement

Read the name of the file and check whether it is file is a directory or not.

C program to check a given filename is a directory or not

The source code to check a given filename is a directory or not is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check a file is a directory or not

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int isDir(const char* fileName)
{
    struct stat path;

    stat(fileName, &path);

    return S_ISREG(path.st_mode);
}

int main()
{
    char fileName[16];
    int ret = 0;

    printf("Enter filename: ");
    scanf("%s", fileName);

    ret = isDir(fileName);

    if (ret == 0)
        printf("Given file is a directory\n");
    else
        printf("Given file is not a directory\n");

    return 0;
}

Output

RUN 1:
Enter filename: hello.txt
Given file is not a directory

RUN 2:
Enter filename: image
Given file is a directory

Explanation

In the above program, we created two functions isDir() and main(). The isDir() function is used to check a given file is a directory or not. Here we used stat() function and S_ISREG() macro.

In the main() function, we created a character array fileName. Then we read the name from the user. Then we checked given file is a directory or not and printed the appropriate message on the console screen.

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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