在 Windows 平台上,使用 FindFirstFile / FindNextFile 進行深度優先遞迴遍歷資料夾,取得所有檔案完整路徑。注意字元集設定(建議 #undef UNICODE 避免編碼問題)。
std::shared_ptr<std::vector<std::string>> 管理動態配置的檔案清單,支援遞迴呼叫時的共享所有權。.、.. 以及特殊檔名(如 -q)。FILE_ATTRIBUTE_DIRECTORY 決定是否遞迴進入子目錄。/*************************************************
File: main.cpp
Copyright: C.L.Wang
Author: Caroline
Date: 2013-11-27
Description: 深度優先遞迴遍歷目錄中所有的檔案
Email: morndragon@126.com
**************************************************/
#undef UNICODE
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <cstring>
#include <windows.h>
std::shared_ptr<std::vector<std::string>> fileList(const std::string& folder_path) {
static std::shared_ptr<std::vector<std::string>> folder_files(
new std::vector<std::string>);
WIN32_FIND_DATA FindData;
HANDLE hError;
int file_count = 0;
std::string file_path(folder_path);
std::string full_file_path;
file_path.append("/*.*");
hError = FindFirstFile(file_path.c_str(), &FindData);
if (hError == INVALID_HANDLE_VALUE) {
std::cout << "failed to search files." << std::endl;
return nullptr;
}
while (FindNextFile(hError, &FindData)) {
if (0 == strcmp(FindData.cFileName, ".") ||
0 == strcmp(FindData.cFileName, "..") ||
0 == strcmp(FindData.cFileName, "-q")) {
continue;
}
full_file_path.append(folder_path);
full_file_path.append("/");
full_file_path.append(FindData.cFileName);
++file_count;
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
fileList(full_file_path);
} else {
folder_files->push_back(full_file_path);
}
full_file_path.clear();
}
return folder_files;
}
int main() {
std::shared_ptr<std::vector<std::string>> folder_files;
folder_files = fileList("E:/Picture/shoes3");
if (folder_files) {
for (size_t i = 0; i != folder_files->size(); ++i) {
std::cout << i + 1 << " : " << (*folder_files)[i] << std::endl;
}
}
return 0;
}
/,Windows API 也接受。FindFirstFileW 並配合 std::wstring。