c++ 递归遍历文件夹下所有指定后缀的文件

只在windows下测试通过,Linux没有测试。

string p;
void getFiles(string path, vector<string>& files, string postfix)
{
	//文件句柄    
	long   hFile = 0;
	//文件信息    
	struct _finddata_t fileinfo;
	
	string current_path = path + "/*.*";
	if ((hFile = _findfirst(current_path.c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之    
			//如果不是,加入列表    
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files, postfix);
			}
			else
			{
				if (postfix.size() == 0 || (postfix.size() > 0 && (postfix == strchr(fileinfo.name, '.'))))
				{
					string fullpath = p + "\\" + fileinfo.name;
					files.push_back(fullpath);
				}
					
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

最前面的 string p;必须在前面,否则就不能返回全路径。另外postfix == strchr(fileinfo.name, '.')这句话确实起到了过滤后缀名的最用,在这里string可以和char*作比较。如果是txt文件strchr(fileinfo.name, '.')返回的是“.txt”。

下面是一套完整代码备用:

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

string p;
void getFiles(string path, vector<string>& files, string postfix)
{
	//文件句柄    
	long   hFile = 0;
	//文件信息    
	struct _finddata_t fileinfo;
	
	string current_path = path + "/*.*";
	if ((hFile = _findfirst(current_path.c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之    
			//如果不是,加入列表    
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files, postfix);
			}
			else
			{
				if (postfix.size() == 0 || (postfix.size() > 0 && (postfix == strchr(fileinfo.name, '.'))))
				{
					string fullpath = p + "\\" + fileinfo.name;
					files.push_back(fullpath);
				}
					
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}


/*
* argv[1]: 文件夹目录
* argv[2]: 文件后缀
*/
int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		printf("please input the folder path and postfix.\n" \
			"argv[1]:folder path\n"\
			"argv[2]:postfix\n");
		return 0;
	}
	vector<string> files;

	//获取该路径下的所有jpg文件
	//getFiles(argv[1], argv[2], files);
	//get_files(argv[1], argv[2], files);
	getFiles(argv[1], files, argv[2]);
	ofstream outf;
	outf.open("fileName.txt");
	int size = files.size();
	for (int i = 0; i < size; i++)
	{
		outf << files[i].c_str() << endl;
		//cout<<files[i].c_str()<<endl;
	}
	return 0;
}

 

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

落花逐流水

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值