#include <iostream> #include <vector> #include <string> #include <queue> #include <io.h> using namespace std; void traverseDir(char *dir,vector<string> &vfile) { //判断目录结构// char trans_dir[256]; trans_dir[0]=‘\0‘; if( dir[strlen(dir)-1] ==‘\\‘) { int i=0; int dir_len = strlen(dir); for( i = 0; i < dir_len; ++i) { trans_dir[i] = dir[i]; } trans_dir[i++] = ‘*‘; trans_dir[i++] = 0; } if( dir[strlen(dir)-1]!=‘*‘ && dir[strlen(dir)-1]!=‘\\‘) { int i=0; int dir_len = strlen(dir); for( i = 0; i < dir_len; ++i) { trans_dir[i] = dir[i]; } trans_dir[i++] = ‘\\‘; trans_dir[i++] = ‘*‘; trans_dir[i++] = 0; } dir = trans_dir; _finddata_t fileDir; long lfDir; queue<string> queue_dir;////用队列实现递归 queue_dir.push(string(dir)); while( !queue_dir.empty()) { string curDir = queue_dir.front(); if( (lfDir = _findfirst(curDir.c_str(),&fileDir))!=-1l )//is -1l no file found { while( _findnext(lfDir,&fileDir)==0 ) { if((fileDir.attrib>=16 && fileDir.attrib<=23) || (fileDir.attrib>=48 && fileDir.attrib<=55))//是目录,加入队列 { if( fileDir.name[0]!=‘.‘)//不是当前目录* 且不是上一层目录** { string tmpstr = curDir;//减去最后一个*号 tmpstr.erase(tmpstr.end()-1); tmpstr.append(string(fileDir.name)); tmpstr.append("\\*"); queue_dir.push(tmpstr);//把当前目录放到队列中以便下一次遍历 } } else { string tmpfilename = curDir; tmpfilename.erase(tmpfilename.end()-1); vfile.push_back(tmpfilename.append(string(fileDir.name))); } } } queue_dir.pop(); } } int main() { #if 1 vector<string > vfile; vfile.clear(); char *dir = "F:\\fight_demo\\Resource\\movies\\1\\NonViolence"; traverseDir(dir,vfile); vector<string >::iterator it_begin = vfile.begin(); vector<string >::iterator it_end = vfile.end(); for( ; it_begin != it_end; ++it_begin ) { cout<<*it_begin<<endl; } #endif return 0; }
传入的目录dir可以是:
"c:\\TMEP"
"c:\\TMEP\\"
"c:\\TMEP\\*"