Fai*_*Dev 72

好吧,我们在某个时间点都是n0obs.问问题没问题.这是一个简单的函数,它正是这样做的:

#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!
}
Run Code Online (Sandbox Code Playgroud)

  • 发生故障时,`GetFileAttributes()`返回`INVALID_FILE_ATTRIBUTES`.你必须使用`GetLastError()`来找出实际失败的原因.如果它返回"ERROR_PATH_NOT_FOUND","ERROR_FILE_NOT_FOUND","ERROR_INVALID_NAME"或"ERROR_BAD_NETPATH",那么它确实不存在.但是如果它返回大多数其他错误,那么在指定的路径上实际存在某些东西,但这些属性根本无法访问. (8认同)
  • 对于那些对此答案感到磕磕绊绊的人,请记住上面的代码是ANSI而不是Unicode.对于现代Unicode,最好采用LPCTSTR参数,例如其他stackoverflow答案中的代码段:http://stackoverflow.com/a/6218445.(LPCTSTR将由编译器转换为`wchar_t*`.).然后,您可以将支持Unicode的函数包装为C++`std :: wstring`而不是`std :: string`. (3认同)

Sim*_*ier 8

如果链接到shell轻量级API(shlwapi.dll)没问题,可以使用PathIsDirectory函数


小智 6

此代码可能有效:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 
Run Code Online (Sandbox Code Playgroud)