只在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;
}

 

 

 

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐