#include <iostream> #include <iomanip> #include <fstream> #include <cstdio> #include <stack> #include <windows.h> using namespace std; /* * 遍历lpszPath下所有文件及文件夹,并按顺序显示其中的内容. */ /* * 如果扫描到文件夹,则将其存入 Dirs 队列中,并显示名称, * 如果扫描到文件,则显示其名称; * 当前文件夹处理完毕后就处理其下一级文件夹,下一级文件夹从队 * 列中得到. */ void function( LPCTSTR lpszPath,ostream & out) { //开始查找; stack< TCHAR *> Dirs; stack< int > DirDepth; TCHAR *tmp= new TCHAR [lstrlen(lpszPath)+1]; lstrcpy(tmp,lpszPath); if (tmp[lstrlen(tmp)-1]== '\\' ) tmp[lstrlen(tmp)-1]= '\0' ; TCHAR szFind[MAX_PATH*2]; TCHAR szFile[MAX_PATH*2]; TCHAR *curdir; int curdepth=1; //当前文件夹的深度 Dirs.push(tmp); DirDepth.push(curdepth); for (;!Dirs.empty();) { curdir=Dirs.top(); curdepth=DirDepth.top(); Dirs.pop(); DirDepth.pop(); lstrcpy(szFind,curdir); lstrcat(szFind, "\\*.*" ); // 找所有文件 WIN32_FIND_DATA wfd; HANDLE hFind = FindFirstFile(szFind, &wfd); if (hFind != INVALID_HANDLE_VALUE) // 如果找到 { if (curdepth >1) out<< " " ; for ( int i=1;i<curdepth-1;++i) out<< '|' << " " ; out<< '+' <<curdir<<endl; do { if (wfd.cFileName[0] == '.' ) continue ; // 过滤"." ".." 这两个目录 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { wsprintf(szFile, "%s\\%s" , curdir, wfd.cFileName); //function(szFile); // 如果找到的是目录,则进入此目录进行递归 TCHAR * tmp= new TCHAR [lstrlen(szFile)+2]; lstrcpy(tmp,szFile); Dirs.push(tmp); DirDepth.push(curdepth+1); } else { //输出文件名 out<< " " ; for ( int i=1;i<curdepth;++i) out<< '|' << " " ; out<<wfd.cFileName<<endl; } } while (FindNextFile(hFind, &wfd)); } // if delete [] curdir; curdir = NULL; FindClose(hFind); // 关闭查找句柄 } // for() } int main( int argc, char *argv[]) { ofstream fout( "遍历结果.txt" ); if (argc<=1) { cerr<<endl<< "文件夹遍历,请输入路径:" ; TCHAR path[MAX_PATH]; cin>>path; function(path,fout); } else { function(argv[1],fout); } return 0; } |
联系客服