查看windows下目录是否存在[C++ Windows API]

 

如下。为windowsapi方法。如果项目支持的话,也可以选用C++17提供的标准库函数。

标准库函数参考

std::filesystem::exists - cppreference.com

bool isDir  = std::filesystem::is_directory(path);
bool exists = std::filesystem::exists(path);

WindowsAPI

How to check if directory exist using C++ and winAPI - Stack Overflow

C++ directory exists (programcreek.com)

如下内容节选stackoverflow,为方便上网不方便的同学:

方法1.85个赞,看评论字符串对于可能有点问题。我选用的是方法2.

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

方法2

5个赞,我选用的此,比较简单。

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

方法3

1一个赞,其实和方法2一样,但没有2高大上。如下

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

 

posted @ 2021-11-17 17:34  逃跑的红薯  阅读(926)  评论(0)    收藏  举报