检查文件是目录还是文件

Joo*_*kia 28 c posix

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 56

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 在考虑符号链接的情况下,使用lstat()而不是stat(),因为它不遵循符号链接. (5认同)
  • 在[检查目录是否存在]中至少有一个很好的讨论(http://stackoverflow.com/questions/3828192/checking-if-a-directory-exists-in-unix-system-call/),其中`stat讨论了`和`lstat()`,并概述了完整的POSIX文件类型集.我很想把这个问题复制到那个问题上.代码也应该检查`stat()`的结果,并适当地处理错误. (3认同)

ism*_*ail 20

使用S_ISDIR宏:

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

  • 理想情况下,代码会检查`stat`是否有效:`if(stat(path,&statbuf)!= 0)返回0;` - 因为不存在的对象不是目录,如果你没有权限对于`stat()`它,它也可能不存在(即使报告的错误与权限有关). (3认同)
  • @JonathanLeffler,你是绝对正确的,更新了代码。 (2认同)