写一个读取文件夹下所有文件的程序,可以按需求添加对文件名的要求
1.Windows
int get_files(std::string fileFolderPath, std::string fileExtension, std::vector<std::string>&file)
{
std::string fileFolder = fileFolderPath + "\\*" + fileExtension;
std::string fileName;
struct _finddata_t fileInfo;
long long findResult = _findfirst(fileFolder.c_str(), &fileInfo);
if (findResult == -1)
{
_findclose(findResult);
return 0;
}
bool flag = 0;
do
{
fileName = fileFolderPath + "\\" + fileInfo.name;
if (fileInfo.attrib == _A_ARCH)
{
file.push_back(fileName);
}
} while (_findnext(findResult, &fileInfo) == 0);
_findclose(findResult);
}
所需的头文件
#include <iostream>
#include <io.h>
#include <vector>
#include <string>
2.Linux
void GetFileNames(string path,vector<string>& filenames)
{
DIR *pDir;
struct dirent* ptr;
string filename, second;
if(!(pDir = opendir(path.c_str())))
return;
while((ptr = readdir(pDir))!=0) {
//跳过.和..文件
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
continue;
filename = ptr->d_name;
// if(con)//也可以添加对文件名的要求
// filenames.push_back(filename);
filenames.push_back(filename);
}
closedir(pDir);
sort(filenames.begin(), filenames.end());
}
所需的头文件
#include <iostream>
#include <vector>
#include <dirent.h> //Dir头文件
#include <string.h>
#include <algorithm>
2020-10-13更新
1.通过opencv的glob获取文件
void GetFileNamesByGlob(cv::String path,vector<cv::String>& filenames, string con)
{
cv::glob(path, filenames, false);//不递归
for(size_t i = 0; i < filenames.size(); ++i)
{
std::cout<<filenames[i]<<std::endl;
}
}
需要头文件
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
2.对文件筛选并按数字排序
//con:文件格式 form:文件命名形式
void GetFileNames(string path,vector<string>& filenames, string con, string form)
{
DIR *pDir;
struct dirent* ptr;
string filename, format, name, name2;
if(!(pDir = opendir(path.c_str())))
return;
while((ptr = readdir(pDir))!=0) {
//跳过.和..文件
if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
continue;
filename = ptr->d_name;
format = filename.substr(filename.find("."), filename.length());
//name = filename.substr(0, filename.find("."));
name = filename.substr(form.length(), filename.find(".") - form.length());
cout<<filename<<"\t"<<name<<endl;
//cout<<format<<endl;
if(format == con)//也可以添加对文件名的要求
filenames.push_back(name);
//filenames.push_back(filename);
}
closedir(pDir);
//sort(filenames.begin(), filenames.end());
//string 类型的数字比较大小有问题, 所以转成int在排序
sort(filenames.begin(), filenames.end(), [](string a, string b){
return stoi(a) < stoi(b);
});
}
举例 我的文件是 img_1.jpg 的形式
//输入文件和输出文件路径
string img_dir = "/media/jinye/DADA-D5FC/mlz/2020_09iphone xr/calibration2/";
string img_format = ".jpg";//, laser_format = ".pcd";//格式
string img_shape = "img";//, laser_shape = "scanf";
//读取图片信息
vector<string> img_names;
GetFileNames(img_dir, img_names, img_format, img_shape);
cout<<"图片读取完成"<<endl;