#include <windows.h> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <io.h> using namespace std; // 头文件要求: vector, string // 命名空间: std #define MAX_PATH_LENGTH 64 // 遍历结果保存结构体 // Filelist 为文件列表 // Foldlist 为文件夹列表 struct FoldInfo { vector<string> Filelist; vector<string> FoldList; }; //遍历文件夹,FolderPath为要遍历的文件夹路径。Filter为遍历文件夹的过滤器,例如*.txt等 bool FindFolder(const char* FolderPath, const char* Filter, FoldInfo &info); bool FindFolder(const char* FolderPath, const char* Filter, FoldInfo &info) { string TargetName; int nPathLen = MAX_PATH_LENGTH; char* pChPath = new char[nPathLen]; sprintf_s(pChPath, nPathLen, "%s/%s", FolderPath, Filter); WIN32_FIND_DATAA fileFindData; HANDLE hFind = ::FindFirstFileA((pChPath), &fileFindData); if (hFind == INVALID_HANDLE_VALUE) { delete pChPath; return false; } do { if (!strcmp(fileFindData.cFileName,".") || !strcmp(&fileFindData.cFileName[0] , "..")) { continue; } sprintf_s(pChPath, nPathLen, "%s/%s", FolderPath, fileFindData.cFileName); //文件的完整路径 TargetName = fileFindData.cFileName; if (fileFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { info.FoldList.push_back(TargetName) ; }else{ info.Filelist.push_back(TargetName) ; } }while (::FindNextFileA(hFind, &fileFindData)); FindClose(hFind); delete pChPath; return true; } void print(string data) { cout << data << endl; } int main(int argc, char** argv) { if (argc < 2) { MessageBoxA(0, "Please provide a Path!", "Error", MB_OKCANCEL); return -1; } if (_access(argv[1], 0) == -1) { MessageBoxA(0, "Path Is Not Exist!", "Error", MB_OKCANCEL); return -1; } FoldInfo fi; FindFolder(argv[1], "*.*", fi); cout << "Fold List\n------------------------------\n"; for_each(fi.FoldList.begin(), fi.FoldList.end(), print); cout <<"\n\n\n"; cout << "File List\n------------------------------\n"; for_each(fi.Filelist.begin(), fi.Filelist.end(), print); return 0; }