我想检查给定的目录是否存在。我知道如何在 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. */
}
But I need a portable way of doing this .. Is there any way to check if a directory exists no matter what OS Im using? Maybe C standard library way?
我知道我可以使用预处理器指令并在不同的操作系统上调用这些函数,但这不是我要求的解决方案。
我最终得到了这个,至少现在是这样:
#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;
}