windows cplusplus 实现文件的查找与遍历
时间: 2024-01-25 08:03:56 浏览: 26
以下是 Windows C++ 实现文件的查找与遍历的示例代码:
```cpp
#include <iostream>
#include <windows.h>
using namespace std;
void traverseDirectory(const char* path) {
WIN32_FIND_DATA findData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char* fullPath = new char[MAX_PATH];
sprintf(fullPath, "%s\\*", path);
hFind = FindFirstFile(fullPath, &findData);
if (hFind == INVALID_HANDLE_VALUE) {
cout << "Failed to find first file" << endl;
return;
}
do {
if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) {
continue;
}
sprintf(fullPath, "%s\\%s", path, findData.cFileName);
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
cout << fullPath << " (directory)" << endl;
traverseDirectory(fullPath);
} else {
cout << fullPath << " (file)" << endl;
}
} while (FindNextFile(hFind, &findData) != 0);
FindClose(hFind);
delete[] fullPath;
}
int main() {
char path[MAX_PATH];
cout << "Enter directory path: ";
cin >> path;
traverseDirectory(path);
return 0;
}
```
该示例代码中,`traverseDirectory` 函数接收一个文件夹路径,使用 `FindFirstFile` 和 `FindNextFile` 函数遍历该文件夹下的所有文件和子文件夹,并输出它们的路径和类型(文件或文件夹)。如果遍历到的是一个文件夹,则递归调用 `traverseDirectory` 函数遍历该文件夹下的所有文件和子文件夹。最后,使用 `FindClose` 函数关闭查找句柄,释放内存。在 `main` 函数中,用户输入文件夹路径,并调用 `traverseDirectory` 函数进行遍历。