40

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

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

| improve this question | |
79

well we were all n0obs at some point in time. No problem in asking. 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!
}
| improve this answer | |
  • 8
    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 2: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: 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 3 '15 at 10:17
8

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

| improve this answer | |
6

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 
| improve this answer | |
4

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);
}
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.