c++遍历目录下的所有文件

本博实现遍历指定目录下的所有文件(夹),以及输出指定类型的文件


代码如下:


#include <iostream>
#include <io.h>
#include <string>
using namespace std;

//遍历该目录下的所有文件(夹)
void dir(string path)
{
	long hFile = 0;
	struct _finddata_t fileInfo;
	string pathName, excName;
	// \\*代表要遍历所有的类型
	if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1)
	{
		return;
	}
	do
	{
		//判断文件的属性是文件夹还是文件
		cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
	} while (_findnext(hFile,&fileInfo)==0);
	_findclose(hFile);
	return;

}
//遍历该目录下的.txt文件
void dir_custom(string path, string type)
{
	long hFile = 0; //句柄
	struct _finddata_t fileInfo;
	string pathName;
	if ((hFile = _findfirst(pathName.assign(path).append("\\*.*").c_str(), &fileInfo)) == -1)
	{
		return;
	}
	do 
	{
		const char* s = fileInfo.name;
		const char* t = type.data();

		if (fileInfo.attrib&_A_SUBDIR) //是子文件夹
		{
			cout << "[Folder]:" <<fileInfo.name << endl;
			
			//遍历子文件夹中的文件(夹),查看是否有txt文件
			if(strcmp(s,".")==0 || strcmp(s,"..")==0) //子文件夹目录是.或者..
				continue;
			string sub_path = path + "\\" + fileInfo.name;
			cout << sub_path << endl;
			dir_custom(sub_path, type);

		}
		else //判断是不是txt文件
		{
			
			if (strstr(s,t))
			{
				cout << fileInfo.name << "\t" << path << "\t" << fileInfo.size << " bytes.\n";

			}
		}
	} while (_findnext(hFile,&fileInfo)==0);
	return;
}

int main()
{
	//给定目录
	string path = "G:\\test";
	//遍历该目录下的所有文件(夹)
	dir(path);

	cout << endl << endl;
	//输出该目录下的所有type类型的文件
	string type = ".txt";
	dir_custom(path, type);


	system("pause");
	return 0;
}

运行效果,感觉有点慢- -:

然后我实际上是创建了一个test文件夹:

参考博客:

https://blog.csdn.net/abcjennifer/article/details/18147551

https://www.cnblogs.com/Pillar/p/4206452.html

https://blog.csdn.net/sinat_31771313/article/details/79207105

https://blog.csdn.net/a342500329a/article/details/83855774

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

keneyr

老爷~给小的赏点盘缠吧555~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值