C++用FindFirstFile、FindNext递归遍历硬盘的文件

xiaoxiao2021-02-28  58

关于 WIN32_FIND_DATA 的数据结构

typedef struct _WIN32_FIND_DATA {    DWORD dwFileAttributes; //文件属性

   FILETIME ftCreationTime; // 文件创建时间

   FILETIME ftLastAccessTime; // 文件最后一次访问时间

   FILETIME ftLastWriteTime; // 文件最后一次修改时间

   DWORD nFileSizeHigh; // 文件长度高32位

   DWORD nFileSizeLow; // 文件长度低32位

   DWORD dwReserved0; // 系统保留

   DWORD dwReserved1; // 系统保留

   TCHAR cFileName[ MAX_PATH ]; // 长文件名

   TCHAR cAlternateFileName[ 14 ]; // 8.3格式文件名

} WIN32_FIND_DATA, *PWIN32_FIND_DATA; #include <iostream> #include <vector> #include <windows.h> using namespace std; class SearchFile { private: vector<string> result; public: vector<string> getResult() { auto t = result; result.clear(); return t; } bool search(char *path="C:\\",char *file="exe") { HANDLE hFile; char buffer[MAX_PATH]={0,}; WIN32_FIND_DATA pNextInfo; //搜索得到的文件信息将储存在pNextInfo中; sprintf(buffer,"%s\\*.*",path); hFile = FindFirstFile(buffer,&pNextInfo);//请注意是 &pNextInfo , 不是 pNextInfo; if(!hFile){ return false; } string t; //cout << buffer << endl; while(FindNextFile(hFile,&pNextInfo)) { if(pNextInfo.cFileName[0] == '.')//过滤.和.. continue; //cout << pNextInfo.cFileName << endl; if(pNextInfo.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) { ZeroMemory(buffer,MAX_PATH); sprintf(buffer,"%s\\%s",path,pNextInfo.cFileName); //cout << buffer << endl; search(buffer,file); } t.assign(path); t+='\\'; t.append(pNextInfo.cFileName); int len = strlen(file); if(t.substr(t.size()-len)==file) { result.push_back(t);//对t对象进行深复制 } } return true; } }; int main() { SearchFile s; //设计了一个SearchFile类来搜索文件,调用search成员函数后,再调用getResult()返回查到的结果,如果搜索失败,getResult()返回NULL s.search("C:\\Users\\lxw\\OneDrive\\python35","py"); auto result = s.getResult(); for(int i=0;i<result.size();i++) { cout << result[i] << endl; } return 0; }

这里的IDE用的是CLion;

转载请注明原文地址: https://www.6miu.com/read-2622483.html

最新回复(0)