文件遍历

C++遍历文件夹并显示内容的代码实现
本文提供了一个使用C++语言编写的函数,用于遍历指定路径下的所有文件和文件夹,并按照顺序显示其内容。通过设置队列来管理文件夹和深度信息,该函数能够递归地处理目录结构。

摘抄自网上……

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

  

转载于:https://www.cnblogs.com/chhyong88/archive/2011/12/28/2305150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值