#include <iostream> #include <string.h> #include <io.h> #include <vector> #include <algorithm> using namespace std; void finddir(const string& name,_finddata_t* fl) { vector<string> str; long hd=_findfirst(string(name).append("*.*").c_str(),fl); if(hd==-1){_findclose(hd);return;} do { if(fl->attrib&_A_SUBDIR && (!strcmp(fl->name,".")||!strcmp(fl->name,"..")))continue; if(fl->attrib&_A_SUBDIR){cout<<string(name).append(fl->name).append("\").c_str()<<endl;str.push_back(string(name).append(fl->name).append("\"));continue;} cout<<name.c_str(); cout<<fl->name<<endl; }while(_findnext(hd,fl)!=-1); _findclose(hd); for(auto it=str.begin();it!=str.end();++it)finddir(*it,fl); } int main() { _finddata_t fl; finddir(string("D:\"),&fl); return 0; }
多线程版本
#include "stdafx.h" #include <iostream> // std::cout #include <atomic> // std::atomic #include <thread> // std::thread #include <vector> // std::vector #include <io.h> #include <mutex> #include <thread> #include <chrono> #include <type_traits> #include <string> #include <bitset> using namespace std; #define THREAD_COUNT 32 vector <string> directory; mutex mtx; bitset<THREAD_COUNT> bst; atomic<int> file_count; atomic<int> folder_count; void print_a_dir(string dir) { _finddata_t* fd=new _finddata_t; long hdl=_findfirst(string(dir).append("*.*").c_str(),fd); if(hdl==-1){_findclose(hdl);return;} do { if(fd->attrib&_A_SUBDIR && (fd->name)[0]=='.')continue; if(fd->attrib&_A_SUBDIR){string temp(dir+fd->name+"\");folder_count++;mtx.lock();directory.push_back(temp);mtx.unlock();continue;} file_count++; //cout<<dir<<fd->name<<endl; }while(_findnext(hdl,fd)!=-1); _findclose(hdl); } void thread_func(int th_index) { string dir; while(1) { mtx.lock(); if(directory.empty()){bst[th_index]=1;if(bst.all()){mtx.unlock();return;}mtx.unlock();continue;} dir=directory.back(); directory.pop_back(); mtx.unlock(); bst[th_index]=0; print_a_dir(dir); } } int main () { vector<thread> v_thread; directory.push_back("D:\Documents\"); cout<<directory[0]<<endl; for(int i=0;i<THREAD_COUNT;i++) v_thread.push_back(thread(thread_func,i)); for(auto& th : v_thread )th.join(); cout<<"folder count:"<<folder_count<<endl; cout<<"file count:"<<file_count<<endl; return 0; }