【问题标题】:How can I check if a directory exists?如何检查目录是否存在?
【发布时间】:2012-09-12 17:11:05
【问题描述】:

如何在 C 语言中检查 Linux 上是否存在目录?

【问题讨论】:

标签: c linux directory


【解决方案1】:

您可以使用opendir() 并检查ENOENT == errno 是否失败:

#include <dirent.h>
#include <errno.h>

DIR* dir = opendir("mydir");
if (dir) {
    /* Directory exists. */
    closedir(dir);
} else if (ENOENT == errno) {
    /* Directory does not exist. */
} else {
    /* opendir() failed for some other reason. */
}

【讨论】:

  • 如果该文件夹不存在,如何确认不存在后立即创建?
  • 如果您使用的是 Visual Studio,dirent.h 不可用,请参阅this SO post 了解替代方案
【解决方案2】:

使用以下代码检查文件夹是否存在。它适用于 Windows 和 Linux 平台。

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

int main(int argc, char* argv[])
{
    const char* folder;
    //folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
    folder = "/tmp";
    struct stat sb;

    if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}

【讨论】:

  • 您确定包含的标头是否足够,至少对于 Linux 而言?
  • S_ISDIR 仅适用于 POSIX,不适用于 Windows,请参阅 this SO post
【解决方案3】:

您可以使用stat() 并将struct stat 的地址传递给它,然后检查其成员st_mode 是否设置了S_IFDIR

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

...

char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)
else
  perror("stat()");

【讨论】:

  • 我想知道 S_IFDIRS_ISDIR 的区别,并在 stat 手册页上找到了这个:"POSIX.1-1990 没有描述 S_IFMT、S_IFSOCK、S_IFLNK、S_IFREG , S_IFBLK, S_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX 常量,而是要求使用宏 S_ISDIR() 等。S_IF* 常量出现在 POSIX.1-2001 及更高版本中。”
  • (s.st_mode &amp; S_IFDIR) : "" ? "not " 你好像把?:搞混了
【解决方案4】:

最好的方法可能是尝试打开它,例如只使用@987654321@

请注意,最好尝试使用文件系统资源,并处理由于它不存在而发生的任何错误,而不是先检查然后再尝试。后一种方法存在明显的竞争条件。

【讨论】:

    【解决方案5】:

    根据man(2)stat,您可以在 st_mode 字段上使用 S_ISDIR 宏:

    bool isdir = S_ISDIR(st.st_mode);
    

    旁注,如果您的软件可以在其他操作系统上运行,我建议使用 Boost 和/或 Qt4 来简化跨平台支持。

    【讨论】:

      【解决方案6】:

      您还可以将accessopendir 结合使用来确定目录是否存在,以及名称是否存在但不是目录。例如:

      #include <sys/stat.h>
      #include <dirent.h>
      #include <unistd.h>
      
      /* test that dir exists (1 success, -1 does not exist, -2 not dir) */
      int
      xis_dir (const char *d)
      {
          DIR *dirptr;
      
          if (access ( d, F_OK ) != -1 ) {
              // file exists
              if ((dirptr = opendir (d)) != NULL) {
                  closedir (dirptr); /* d exists and is a directory */
              } else {
                  return -2; /* d exists but is not a directory */
              }
          } else {
              return -1;     /* d does not exist */
          }
      
          return 1;
      }
      

      【讨论】:

      • 不错,但我会将 int xis_dir (char *d) 更改为 int xis_dir (const char *d),因为 d 没有被修改。
      猜你喜欢
      • 2011-02-15
      • 2023-02-22
      • 1970-01-01
      • 2022-08-21
      • 2023-03-09
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多