【发布时间】:2013-08-08 15:15:03
【问题描述】:
我想检查给定目录是否存在。我知道如何在 Windows 上执行此操作:
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
和 Linux:
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. */
}
但是我需要一种可移植的方式来执行此操作.. 无论我使用什么操作系统,有什么方法可以检查目录是否存在?也许C标准库方式?
我知道我可以使用预处理器指令并在不同的操作系统上调用这些函数,但这不是我要求的解决方案。
至少现在我结束了这个:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int dirExists(const char *path)
{
struct stat info;
if(stat( path, &info ) != 0)
return 0;
else if(info.st_mode & S_IFDIR)
return 1;
else
return 0;
}
int main(int argc, char **argv)
{
const char *path = "./TEST/";
printf("%d\n", dirExists(path));
return 0;
}
【问题讨论】:
-
简单地尝试在其中创建一个文件(具有随机文件名)怎么样?
-
请注意,您从此类测试中获得的任何答案都会立即过时。您刚刚检查的目录可以在您使用它时被删除或移动 - 这种类型的代码本质上是错误的。这种“check-then-use”的bug甚至还有it's own Wikipedia page:“在软件开发中,time-of-check to time-of-use(TOCTOU, TOCTTOU or TOC/TOU)是一类由一种竞争条件,涉及检查系统的一部分(例如安全凭证)的状态以及使用该检查的结果。”
-
如果您需要在特定目录中创建文件,只需在该目录中创建文件。如果该目录不存在,您将收到错误消息。并且首先检查目录是否存在 NOT 保证您可以创建该文件,因此无论如何您都必须处理创建错误。
标签: c file directory file-exists