Windows下文件夹遍历(2)

王朝system·作者佚名  2006-01-09
宽屏版  字体: |||超大  

修改了一下程序,使其可以在当前路径下以文件名“遍历结果.txt”输出运行结果;

运行结果改为树形输出方式。

#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;

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;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有