How do you check if a directory exists on Windows in C?

Solution 1:

Do something like this:

BOOL DirectoryExists(LPCTSTR szPath)
{
  DWORD dwAttrib = GetFileAttributes(szPath);

  return (dwAttrib != INVALID_FILE_ATTRIBUTES && 
         (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

The GetFileAttributes() method is included in Kernel32.dll.

Solution 2:

Here's a totally platform-agnostic solution (using the standard C library)

Edit: For this to compile in Linux, replace <io.h> with <unistd.h> and _access with access. For a real platform agnostic solution, use the Boost FileSystem library.

#include <io.h>     // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().

bool DirectoryExists( const char* absolutePath ){

    if( _access( absolutePath, 0 ) == 0 ){

        struct stat status;
        stat( absolutePath, &status );

        return (status.st_mode & S_IFDIR) != 0;
    }
    return false;
}

A Windows-specific implementation that supports both MBCS and UNICODE builds:

#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <tchar.h>

BOOL directory_exists( LPCTSTR absolutePath )
{
  if( _taccess_s( absolutePath, 0 ) == 0 )
  {
    struct _stat status;
    _tstat( absolutePath, &status );
    return (status.st_mode & S_IFDIR) != 0;
  }

  return FALSE;
}

Solution 3:

If linking to the Shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function.

Solution 4:

Another option is the shell function PathFileExists()

PathFileExists() documentation

This function "Determines whether a path to a file system object such as a file or directory is valid."