如何检查目录是否存在?

use*_*915 55 c linux directory

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

hmj*_*mjd 75

您可以使用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. */
}
Run Code Online (Sandbox Code Playgroud)

  • 要使用它,你需要`#include <dirent.h>`. (11认同)

Sam*_*man 35

使用以下代码检查文件夹是否存在.它适用于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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • S_ISDIR 仅适用于 POSIX,不适用于 Windows,请参阅[this SO post](/sf/ask/786724291/) (2认同)

alk*_*alk 15

您可以使用stat()并传递a的地址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()");
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 9

最好的方法可能就是试图打开它,仅opendir()举例来说.

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