I would like to check if a given directory exists. I know how to do this on Windows:
我想检查给定目录是否存在。我知道如何在Windows上操作:
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
and Linux:
和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?
但是我需要一种便携式的方法。有没有办法检查一个目录是否存在,无论我使用什么操作系统?也许是C标准库方式?
I know that I can use preprocessors directives and call those functions on different OSes but thats not the solution Im asking for.
我知道我可以使用预处理指令并在不同的操作系统上调用这些函数,但这不是我所要求的解决方案。
I END UP WITH THIS, AT LEAST FOR NOW:
我的结局是这样的,至少现在是这样:
#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;
}
3 个解决方案
#1
65
stat() works on Linux., UNIX and Windows as well:
stat()在Linux上工作。、UNIX和Windows系统:
#include <sys/types.h>
#include <sys/stat.h>
struct stat info;
if( stat( pathname, &info ) != 0 )
printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
printf( "%s is a directory\n", pathname );
else
printf( "%s is no directory\n", pathname );
#2
2
Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.
使用boost:::文件系统,这将为您提供一种可移植的方式来完成这些工作,并为您抽象出所有难看的细节。
#3
1
You can use the GTK glib to abstract from OS stuff.
您可以使用GTK glib从OS内容中抽象出来。
glib provides a g_dir_open() function which should do the trick.
glib提供了一个g_dir_open()函数,应该可以实现这个功能。
#1
65
stat() works on Linux., UNIX and Windows as well:
stat()在Linux上工作。、UNIX和Windows系统:
#include <sys/types.h>
#include <sys/stat.h>
struct stat info;
if( stat( pathname, &info ) != 0 )
printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
printf( "%s is a directory\n", pathname );
else
printf( "%s is no directory\n", pathname );
#2
2
Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.
使用boost:::文件系统,这将为您提供一种可移植的方式来完成这些工作,并为您抽象出所有难看的细节。
#3
1
You can use the GTK glib to abstract from OS stuff.
您可以使用GTK glib从OS内容中抽象出来。
glib provides a g_dir_open() function which should do the trick.
glib提供了一个g_dir_open()函数,应该可以实现这个功能。