【问题标题】:How to check if directory exist using C++ and winAPI [duplicate]如何使用 C++ 和 winAPI 检查目录是否存在 [重复]
【发布时间】:2012-01-04 06:03:22
【问题描述】:

如何使用 C++ 和 windows API 检查目录是否存在?

【问题讨论】:

标签: c++ winapi directory


【解决方案1】:

这是一个简单的函数,它就是这样做的:

#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!
}

【讨论】:

  • GetFileAttributes() 在发生故障时返回INVALID_FILE_ATTRIBUTES。你必须使用GetLastError() 来找出失败的真正原因。如果它返回ERROR_PATH_NOT_FOUNDERROR_FILE_NOT_FOUNDERROR_INVALID_NAMEERROR_BAD_NETPATH,那么它确实不存在。但如果它返回大多数其他错误,那么在指定路径中确实存在某些东西,但属性根本无法访问。
  • 对于那些偶然发现这个答案的人,请记住,上面的代码是 ANSI 而不是 Unicode。对于现代 Unicode,最好采用 LPCTSTR 参数,例如另一个 stackoverflow 答案中的 sn-p:stackoverflow.com/a/6218445。 (LPCTSTR 将被编译器翻译成wchar_t*。)。然后,您可以包装该 Unicode 感知函数以采用 C++ std::wstring 而不是 std::string
【解决方案2】:

如果你可以链接到 shell 轻量级 API (shlwapi.dll),你可以使用PathIsDirectory function

【讨论】:

    【解决方案3】:

    此代码可能有效:

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

    【讨论】:

      【解决方案4】:

      0.1 秒谷歌搜索:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-11
        • 1970-01-01
        • 2016-09-20
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2013-05-19
        相关资源
        最近更新 更多