如何检查Linux中C目录是否存在?如何检查目录是否存在?
回答
您可以使用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. */
}
最好的方法可能是试图打开它,例如只使用opendir()
。
请注意,它总是最好尝试使用一个文件系统资源,并处理任何错误,因为它不存在,而不仅仅是检查,然后再尝试。后一种方法存在明显的竞争条件。
您可以使用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()");
另外两种方式,也许不太正确的是使用。 第一种,只使用标准库和只有文件:
FILE *f;
f = fopen("file", "r")
if(!f)
printf("there is no file there");
这一条可能在所有的操作系统中使用。
或另一个也用于目录,使用系统调用system()。是最糟糕的选择,但给你另一种方式。对于某人也许有用。
问题是关于目录,而不是文件。你会建议调用'system()',你应该指定传递给它的参数。 –
“*'printf(”那里没有文件“)*”:不能打开文件并不一定意味着它不存在。这样做:代码可能无法“打开”现有文件,例如由于访问权限问题。 – alk
根据man(2)stat可以使用S_ISDIR宏观上的st_mode字段:
bool isdir = S_ISDIR(st.st_mode);
方面说明,我会建议使用升压和/或Qt4的进行跨平台的支持更容易,如果你的软件可以是可行在其他操作系统上。
使用下面的代码来检查文件夹是否存在。它适用于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");
}
}
你确定包含的头文件是否足够用于Linux? – alk
您也可以结合使用access
与opendir
,以确定是否该目录存在,并且,如果名称存在,但不是目录。例如:
/* 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;
}
我同意下面的头是最好的解决方案之一:
#include <stdio.h>
#include <sys/stat.h>
你不需要一些伴随代码的头文件来真正回答这个问题吗? –
这不提供问题的答案。 – alk
- 1. 如何检查目录下是否存在特定目录?
- 2. SVNKit - 检查目录是否存在
- 3. 检查lua中是否存在目录?
- 4. Talend - 检查目录是否存在
- 5. 如何在检查目录是否存在时避免EXC_BAD_ACCESS?
- 6. 如何在Perl中检查Windows上是否存在Unicode目录?
- 7. 如何使用ANT在删除目录之前检查目录是否存在?
- 8. 如何检查目录是否已经存在于MFC(VC++)中?
- 9. 如何检查目录是否存在文件?
- 10. 如何检查是否使用目录存在C++和WINAPI
- 11. 如何检查包含文件的目录是否存在?
- 12. 如何检查一个目录是否存在C
- 13. 如何检查目录中是否存在文件
- 14. 如何检查一个目录是否存在于AppleScriptObjc
- 15. 如何通过PHP检查目录是否存在?
- 16. 如何检查Cordova中是否存在目录?
- 17. 如何检查目录是否存在于linux中。?
- 18. 如何检查FTP目录是否存在
- 19. 如何检查是否一个目录,目录名通配符存在?
- 20. 如何检查IIS目录是否是虚拟目录?
- 21. 检查项目是否存在保存
- 22. Python:检查给定目录中是否存在任何文件
- 23. 如何检查是否在缓存(System.Web.Cache)存在项目?
- 24. Perl LWP :: Simple :: getstore如何检查目标目录中是否存在该文件
- 25. 检查你是否在主目录(linux)
- 26. 如何检查路径的目标是否是目录?
- 27. Cakephp检查是否存在记录
- 28. rethinkdb检查是否存在记录
- 29. 检查是否存在记录
- 30. 检查Dapper是否存在记录ORM
的可能的复制[C更快的方法,以检查是否存在一个目录(HTTP://计算器。 com/questions/9314586/c-fast-way-check-if-a-directory-exists) –