首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 判斷資料夾是否存在(Windows API)

     編輯:關於C++

方法: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 同樣可用,但較重。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved