50

How do I check whether a directory exists using C++ and windows API?

Machavity
  • 30,841
  • 27
  • 92
  • 100
MaSmi
  • 567
  • 1
  • 4
  • 5
  • why not just do `BOOL PathFileExists(pszPath);` as shown in https://msdn.microsoft.com/en-us/library/windows/desktop/bb773584(v=vs.85).aspx ? – Fractal Jun 27 '16 at 19:40
  • Since C++ 17 one doesn't have to rely on platform-specific API's for this: `std::filesystem::exists(dirPath) && std::filesystem::is_directory(dirPath)`. See [docs](https://en.cppreference.com/w/cpp/header/filesystem). – Alexander Malakhov Apr 29 '22 at 13:27

4 Answers4

93

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • 10
    `GetFileAttributes()` returns `INVALID_FILE_ATTRIBUTES` when a failure occurs. You have to use `GetLastError()` to find out what that failure actually is. If it returns `ERROR_PATH_NOT_FOUND`, `ERROR_FILE_NOT_FOUND`, `ERROR_INVALID_NAME`, or `ERROR_BAD_NETPATH` then it really does not exist. But if it returns most any other error, then something actually exists at the specified path but the attributes are simply not accessible. – Remy Lebeau Dec 18 '12 at 02:10
  • 3
    For those stumbling on this answer, keep in mind that the above code is ANSI not Unicode. For modern Unicode, it's better to take a LPCTSTR parameter such as the snippet in this other stackoverflow answer: http://stackoverflow.com/a/6218445. (The LPCTSTR will be translated to `wchar_t*` by the compiler.). You can then wrap that Unicode-aware function to take a C++ `std::wstring` instead of `std::string`. – JasDev Sep 03 '15 at 10:17
10

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

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
5

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 
2

0.1 second Google search:

BOOL DirectoryExists(const char* dirName) {
  DWORD attribs = ::GetFileAttributesA(dirName);
  if (attribs == INVALID_FILE_ATTRIBUTES) {
    return false;
  }
  return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}