方法:GetFileAttributesA
#include <windows.h>
bool dirExists(const string& path) {
DWORD attr = GetFileAttributesA(path.c_str());
if (attr == INVALID_FILE_ATTRIBUTES) return false;
return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
完整程式碼
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
bool dirExists(const string& dirName) {
DWORD ftyp = GetFileAttributesA(dirName.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES) return false;
return (ftyp & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
int main() {
string folder("./Test");
if (dirExists(folder)) cout << "Folder: " << folder << " exist!" << endl;
else cout << "Folder: " << folder << " doesn't exist!" << endl;
string nofolder("./TestNo");
if (dirExists(nofolder)) cout << "Folder: " << nofolder << " exist!" << endl;
else cout << "Folder: " << nofolder << " doesn't exist!" << endl;
return 0;
}
替代方案
- C++17
std::filesystem::exists / is_directory(跨平台、推薦)。
PathFileExists (Shlwapi.lib) 同時檢查檔案/目錄。
FindFirstFile 同樣可用,但較重。