【原创】 遍历指定目录下文件名与文件夹名 c++

 1 #include <windows.h>
 2 #include <vector>
 3 #include <string>
 4 #include <iostream>
 5 
 6 using std::vector;
 7 using std::string;
 8 using std::cout;
 9 using std::endl;
10 
11 // GetAllFilesList
12 // traversal the specified path, get files list of files and sub-folders
13 // string file_path [in] the specified path
14 // vector<string> files_list [out] the files list
15 // vector<string> folders_list [out] the sub-folders list
16 // return value : true -- successful, false -- fail
17 bool GetAllFilesList(string file_path, vector<string> &files_list, vector<string> &folders_list)
18 {
19     bool bRtn = false;
20     if(file_path.empty())
21     {
22         return bRtn;
23     }
24 
25     WIN32_FIND_DATA find_data;
26     HANDLE hFind = FindFirstFileA(file_path.c_str(), &find_data);
27     if(hFind == INVALID_HANDLE_VALUE)
28     {
29         return bRtn;
30     }
31     string find_path = file_path + "\\*.*";
32     hFind = FindFirstFile(find_path.c_str(), &find_data);
33     do
34     {
35         if((string)find_data.cFileName == "." || (string)find_data.cFileName == "..")
36         {
37             continue;
38         }
39 
40         string full_path = file_path + "\\" + find_data.cFileName; 
41         if(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
42         {
43             vector<string> file_list_tmp;
44             vector<string> folder_list_tmp;
45             folders_list.push_back(full_path);
46             GetAllFilesList(full_path, file_list_tmp, folder_list_tmp);
47             if(!file_list_tmp.empty())
48             {
49                 files_list.insert(files_list.end(), file_list_tmp.begin(), file_list_tmp.end());
50             }
51             if(!folder_list_tmp.empty())
52             {
53                 folders_list.insert(folders_list.end(), folder_list_tmp.begin(), folder_list_tmp.end());
54             }
55         }
56         else
57         {
58             files_list.push_back(full_path);
59         }
60     } while(FindNextFile(hFind, &find_data));
61 
62     FindClose(hFind);                                                                                                                                                                                                                            
63 
64     return bRtn;
65 }
posted @ 2012-10-15 22:35  Jim.Ji  阅读(181)  评论(0编辑  收藏  举报