Read the name of the file and check whether it is file is a directory or not.
Program:
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.
Read the name of the file and check whether it is file is a directory or not.
Program:
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer