检查文件是目录还是文件 [英] Checking if a file is a directory or just a file
本文介绍了检查文件是目录还是文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个程序来检查某些东西是文件还是目录.有比这更好的方法了吗?
I'm writing a program to check if something is a file or is a directory. Is there a better way to do it than this?
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int isFile(const char* name)
{
DIR* directory = opendir(name);
if(directory != NULL)
{
closedir(directory);
return 0;
}
if(errno == ENOTDIR)
{
return 1;
}
return -1;
}
int main(void)
{
const char* file = "./testFile";
const char* directory = "./";
printf("Is %s a file? %s.\n", file,
((isFile(file) == 1) ? "Yes" : "No"));
printf("Is %s a directory? %s.\n", directory,
((isFile(directory) == 0) ? "Yes" : "No"));
return 0;
}
推荐答案
您可以调用 stat( )函数,并在 stat 结构,以确定您的路径是否指向常规文件:
You can call the stat() function and use the S_ISREG()
macro on the st_mode
field of the stat structure in order to determine if your path points to a regular file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
请注意,除了常规和目录外,还有其他文件类型,例如设备,管道,符号链接,套接字等.您可能需要考虑这些文件类型.
Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.
这篇关于检查文件是目录还是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文