"#include <windows.h>\n#include \n#include \n#include \n\nusing namespace std;
\nvector files; // 存储文件路径的全局向量\n\nvoid TraverseDirectory(LPCTSTR folderPath) {\n WIN32_FIND_DATA findData; \n HANDLE hFind; \n\n string currentPath = folderPath; \n currentPath += "*.*"; \n\n hFind = FindFirstFile(currentPath.c_str(), &findData); \n if (hFind != INVALID_HANDLE_VALUE) { \n do { \n if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { \n if (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0) { \n string newPath = folderPath; \n newPath += ""; \n newPath += findData.cFileName; \n TraverseDirectory(newPath.c_str()); \n } \n } else { \n string filePath = folderPath; \n filePath += ""; \n filePath += findData.cFileName; \n files.push_back(filePath); \n } \n } while (FindNextFile(hFind, &findData)); \n FindClose(hFind); \n } \n}\n\nDWORD WINAPI ThreadFunc(LPVOID lpParam) { \n TraverseDirectory((LPCTSTR)lpParam); \n return 0; \n}\n\nint main() { \n string folderPath = "C:\path\to\directory"; \n HANDLE hThread; \n DWORD threadId; \n\n hThread = CreateThread(NULL, 0, ThreadFunc, (LPVOID)folderPath.c_str(), 0, &threadId); \n if (hThread == NULL) { \n cerr << "Failed to create thread." << endl; \n return 1; \n } \n\n WaitForSingleObject(hThread, INFINITE); \n\n for (const auto& file : files) { \n cout << file << endl; \n } \n\n CloseHandle(hThread); \n\n return 0; \n}\n"该代码首先定义了一个全局向量 files,用于存储文件的路径。然后,TraverseDirectory 函数通过递归的方式深度优先遍历目录,并将文件路径添加到 files 向量中。ThreadFunc 函数是线程函数,它接收一个目录路径作为参数,并调用 TraverseDirectory 函数进行遍历。在 main 函数中,我们创建一个线程来调用 ThreadFunc 函数,并等待线程结束。最后,我们遍历 files 向量,输出文件路径。\n\n请注意,这只是一个简单的示例代码,可能还有其他的错误处理和线程同步问题需要考虑。

Windows C++ 多线程深度优先递归遍历目录

原文地址: https://www.cveoy.top/t/topic/qgp9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录