文本路徑讀取
在機器學習模型訓練前期,需要對資料、圖像、文本等進行預處理,而如何快速生成資料的文本路徑呢?本文接下來直接使用C++實作文本路徑生成,可查找固定格式如
.jpg
、
.txt
等檔案路徑(絕對路徑或檔案名),然後儲存為
.txt
文本,友善後期圖檔資料讀取使用。
C++代碼實作如下:
#include <io.h>
#include <fstreanm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void GetAllFiles(string path, vector<string>& files, string format)
{
long hfile = ;
struct _finddata_t fileinfo; //用來存儲檔案資訊的結構體
string p;
if(hfile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -) //第一次查找
{
do{
//files.push_back(p.assign(fileinfo.name)); //隻儲存檔案名files.push_back(p.assign(path).appand("\\").append(fileinfo.name)); //儲存檔案路徑和檔案名
}while(_findnext(hfile, &fileinfo) == );
_findclose(hfile)
}
else if((hfile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -)
{
do{
if((fileinfo.attrib & _A_SUBDIR)) //如果查找到的是檔案夾
{
if(strcmp(fileinfo.name, ".") != && strcmp(fileinfo.name, "..") != ) //進入檔案夾查找
{
GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
}
}
else //如果查找的不是檔案夾
{
//files.push_back(p.assign(fileinfo.name)); //隻儲存檔案名 files.push_back(p.assign(path).appand("\\").append(fileinfo.name)); //儲存檔案路徑和檔案名
}
}while(_findnext(hfile, &fileinfo) == );
_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 = ; i<size; i++)
{
ofn<<files[i]<<endl; //寫入檔案
cout<<files[i]<<endl; //輸出到螢幕
}
ofn.close();
cout<<"file number: "<<size<<endl;
system("pause";)
return ;
}
注意:如果format指派出錯會進入死循環。