深度優先搜索遍歷文件夾所有文件, 由於使用windows的函數, 必須要使用C語言;
注意字符集的問題,使用"#undef UNICODE", 屏蔽因字符集所產生的問題;
使用vector<string>存儲所有文件名, 因為要遞歸使用, 所以需要設置為靜態,返回shared_ptr的指針
代碼如下:
/************************************************* File: main.cpp Copyright: C.L.Wang Author: Caroline Date: 2013-11-27 Description: 深度優先遞歸遍歷目錄中所有的文件 Email: [email protected] **************************************************/ #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)) { //過慮".", "..", "-q" 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){ //std::cout << file_count << " " << full_file_path << "<Dir>" << std::endl; fileList(full_file_path); }else{ folder_files->push_back(full_file_path); //std::cout << file_count << " " << full_file_path << std::endl; } full_file_path.clear(); //清空目錄 } return folder_files; } int main(void) { 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; }
作者:csdn博客 Spike_King