Portable way to check if directory exists [Windows/Linux, C]
Since I found that the above approved answer lacks some clarity and the op provides an incorrect solution that he/she will use. I therefore hope that the below example will help others. The solution is more or less portable as well.
/******************************************************************************
* Checks to see if a directory exists. Note: This method only checks the
* existence of the full path AND if path leaf is a dir.
*
* @return >0 if dir exists AND is a dir,
* 0 if dir does not exist OR exists but not a dir,
* <0 if an error occurred (errno is also set)
*****************************************************************************/
int dirExists(const char* const path)
{
struct stat info;
int statRC = stat( path, &info );
if( statRC != 0 )
{
if (errno == ENOENT) { return 0; } // something along the path does not exist
if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
return -1;
}
return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}
stat() works on Linux., UNIX and Windows as well:
#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 );
With C++17 you can use std::filesystem::is_directory
function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path
object which can be constructed with a unicode path.