文件夹下的文件名路径读取(C++)

文本路径读取

在机器学习模型训练前期,需要对数据、图像、文本等进行预处理,而如何快速生成数据的文本路径呢?本文接下来直接使用C++实现文本路径生成,可查找固定格式如.jpg.txt 等文件路径(绝对路径或文件名),然后保存为.txt 文本,方便后期图片数据读取使用。


C++代码实现如下:

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

void GetAllFiles(std::string path, std::vector<std::string>& files, std::string format)
{
	long long hfile = 0;
	struct _finddata_t fileinfo;
	std::string p;
	if ((hfile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -1)
	{
		do
		{
			//files.push_back(p.assign(fileinfo.name)); //save file name
			files.push_back(p.assign(path).append("\\").append(fileinfo.name)); // save file path
		} while (_findnext(hfile, &fileinfo) == 0);
		_findclose(hfile);
	}
	else if ((hfile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do 
		{
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
				}
			}
			else
			{
				//files.push_back(p.assign(fileinfo.name));  
				//files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hfile, &fileinfo) == 0);
		_findclose(hfile);
	}
}

int main()
{
	string filepath = "D:\\path..."; //文件根目录
	vector<string> files;
	char *dstAll = "path.txt";
	//读取所以格式为jpg的文件
	string format = ".jpg";
	GetAllFiles(filepath, files, format);
	ofstream ofn(distAll);
	int size = files.size();
	for(int i = 0; i<size; i++)
	{
		ofn<<files[i]<<endl; //写入文件
		cout<<files[i]<<endl; //输出到屏幕
	}
	ofn.close();
	cout<<"file number: "<<size<<endl;
	system("pause";)
	return 0;
}

注意:如果format赋值出错会进入死循环。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值