C++基礎,輸出目錄下的所有檔案的路徑
阿新 • • 發佈:2021-01-30
技術標籤:C++基礎學習筆記c++輸出目錄下所有檔案路徑目錄路徑
附上程式碼,做個筆記。
/* 輸出目錄下面的所有檔案的路徑,如果有子目錄,會進到子目錄 */ #include <iostream> #include <io.h> using namespace std; void listFiles(string dir); int main() { //目錄路徑 string dir = "C:\\Users\\JSM-SQ\\Desktop\\face\\att_faces"; listFiles(dir); system("pause"); return 1; } void listFiles(string dir) { //在目錄後面加上"\\*.*"進行第一次搜尋 string newDir = dir + "\\*.*"; //用於查詢的控制代碼 intptr_t handle; struct _finddata_t fileinfo; //第一次查詢 handle = _findfirst(newDir.c_str(), &fileinfo); if (handle == -1) { cout << "無檔案" << endl; system("pause"); return; } do { if (fileinfo.attrib & _A_SUBDIR) {//如果為資料夾,加上資料夾路徑,再次遍歷 if (strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0) continue; // 在目錄後面加上"\\"和搜尋到的目錄名進行下一次搜尋 newDir = dir + "\\" + fileinfo.name; listFiles(newDir.c_str()); } else{ string file_path = dir + "\\" + fileinfo.name; cout << file_path.c_str() << endl; } } while (!_findnext(handle, &fileinfo)); _findclose(handle); return; }