2012-09-20 52 views
39

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

+0

的可能的复制[C更快的方法,以检查是否存在一个目录(HTTP://计算器。 com/questions/9314586/c-fast-way-check-if-a-directory-exists) –

回答

44

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

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. */ 
} 
+5

要使用这个,你需要'#include '。 –

+0

如果该文件夹不存在,那么在确认它不存在后,如何立即创建一个文件夹? – Pototo

+0

默认包含“errno”吗?根据手册页 – peter

8

最好的方法可能是试图打开它,例如只使用opendir()

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

13

您可以使用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()"); 
-5

另外两种方式,也许不太正确的是使用。 第一种,只使用标准库和只有文件:

FILE *f; 
f = fopen("file", "r") 
if(!f) 
    printf("there is no file there"); 

这一条可能在所有的操作系​​统中使用。

或另一个也用于目录,使用系统调用system()。是最糟糕的选择,但给你另一种方式。对于某人也许有用。

+2

问题是关于目录,而不是文件。你会建议调用'system()',你应该指定传递给它的参数。 –

+2

“*'printf(”那里没有文件“)*”:不能打开文件并不一定意味着它不存在。这样做:代码可能无法“打开”现有文件,例如由于访问权限问题。 – alk

4

根据man(2)stat可以使用S_ISDIR宏观上的st_mode字段:

bool isdir = S_ISDIR(st.st_mode); 

方面说明,我会建议使用升压和/或Qt4的进行跨平台的支持更容易,如果你的软件可以是可行在其他操作系统上。

24

使用下面的代码来检查文件夹是否存在。它适用于Windows平台上的Windows &。

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

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

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

你确定包含的头文件是否足够用于Linux? – alk

1

您也可以结合使用accessopendir,以确定是否该目录存在,并且,如果名称存在,但不是目录。例如:

/* test that dir exists (1 success, -1 does not exist, -2 not dir) */ 
int 
xis_dir (char *d) 
{ 
    DIR *dirptr; 

    if (access (d, F_OK) != -1) { 
     // file exists 
     if ((dirptr = opendir (d)) != NULL) { 
      closedir (dirptr); 
     } else { 
      return -2; /* d exists, but not dir */ 
     } 
    } else { 
     return -1;  /* d does not exist */ 
    } 

    return 1; 
} 
-2

我同意下面的头是最好的解决方案之一:

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

你不需要一些伴随代码的头文件来真正回答这个问题吗? –

+1

这不提供问题的答案。 – alk

相关问题