检查文件是目录还是文件

我正在编写一个程序来检查某些东西是文件还是目录。 有没有比这更好的方法呢?

#include  #include  #include  #include  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 %sa file? %s.\n", file, ((isFile(file) == 1) ? "Yes" : "No")); printf("Is %sa directory? %s.\n", directory, ((isFile(directory) == 0) ? "Yes" : "No")); return 0; } 

您可以调用stat()函数并在stat结构的st_mode字段上使用S_ISREG()宏,以确定您的路径是否指向常规文件:

 #include  #include  #include  int is_regular_file(const char *path) { struct stat path_stat; stat(path, &path_stat); return S_ISREG(path_stat.st_mode); } 

请注意除常规目录之外还有其他文件类型,如设备,管道,符号链接,套接字等。您可能需要考虑这些类型。

使用S_ISDIR宏:

 int isDirectory(const char *path) { struct stat statbuf; if (stat(path, &statbuf) != 0) return 0; return S_ISDIR(statbuf.st_mode); } 

是的,还有更好的。 检查statfstat函数

通常,您希望使用结果以primefaces方式执行此检查,因此stat()无用。 相反,首先open()文件只读,然后使用fstat() 。 如果它是一个目录,则可以使用fdopendir()来读取它。 或者您可以尝试将其打开以进行写入,如果它是目录,则打开将失败。 某些系统(POSIX 2008,Linux)也有一个O_DIRECTORY扩展open ,如果名称不是目录,则调用失败。

如果你想要一个目录,使用opendir()方法也很好,但你不应该在之后关闭它; 你应该继续使用它。