前言
工作过程中需要读取指定文件夹下同类型文件,并根据文件名最后几位数字进行排序。当文件名全为数字时,直接根据数字就可进行排序,但是,如果文件名是含有非数字型变量(如abc _-)时,就无法通过上述方法直接进行排序,读取文件时默认存储在string类型变量中,但是该变量通过最后几位数字来进行排序。对winwows文件排序功能有过了解,得知其将文件名转化为二进制进行排序,这种方法过于复杂。
文件名如下所示:
170818-1743-LM120_401.pcd
170818-1743-LM120_402.pcd
170818-1743-LM120_403.pcd
...
170818-1743-LM120_4001.pcd
170818-1743-LM120_4002.pcd
...
170818-1743-LM120_40001.pcd
1. 读取指定文件夹下同类型文件
首先读取文件夹下同类型文件:
read_filelists(const std::string& dir_path,std::vector<std::string>& out_filelsits,std::string type){
struct dirent *ptr;
DIR *dir;
dir = opendir(dir_path.c_str());
out_filelsits.clear();
while ((ptr = readdir(dir)) != NULL){
std::string tmp_file = ptr->d_name;
if (tmp_file[0] == '.')continue;
if (type.size() <= 0){
out_filelsits.push_back(ptr->d_name);
}else{
if (tmp_file.size() < type.size())continue;
std::string tmp_cut_type = tmp_file.substr(tmp_file.size() - type.size(),type.size());
if (tmp_cut_type == type){
out_filelsits.push_back(ptr->d_name);
}
}
}
}
const std::string& dir_path:文件夹路径名
std::vector<std::string>& out_filelsits:存储文件名容器
std::string type:文件类型名
2. 按照文件名最后几位数字进行排序
在进行排序时,如果直接对容器内string进行排序会出现如下乱序版本:
170818-1743-LM120_401.pcd
170818-1743-LM120_4001.pcd
170818-1743-LM120_40001.pcd
...
170818-1743-LM120_402.pcd
170818-1743-LM120_4002.pcd
...
170818-1743-LM120_403.pcd
显然不是我们需要的顺序,出现这种情况,猜测是与string类型的编码特性有关,希望大神告知。
正确排序代码:
bool computePairNum(std::pair<double,std::string> pair1,std::pair<double,std::string> pair2)
{
return pair1.first < pair2.first;
}
void sort_filelists(std::vector<std::string>& filists,std::string type)
{
if (filists.empty())return;
std::vector<std::pair<double,std::string> > filelists_pair;
for (int i = 0; i < filists.size(); ++i) {
std::string tmp_string = filists[i];
int npos = tmp_string.find_last_of("_");
std::string tmp_num_string = tmp_string.substr(npos+1,tmp_string.size() - type.size()-4);
double tmp_num = atof(tmp_num_string.c_str());
std::pair<double,std::string> tmp_pair;
tmp_pair.first = tmp_num;
tmp_pair.second = tmp_string;
filelists_pair.push_back(tmp_pair);
}
std::sort(filelists_pair.begin(),filelists_pair.end(),computePairNum);
filists.clear();
for (int i = 0; i < filelists_pair.size(); ++i) {
filists.push_back(filelists_pair[i].second);
}
}
在函数sort_filelists中,使用find_last_of("_")函数找到最后一个"_"符号,并进行分割出来,这一步就是把string类型文件名最后几位数字对应索引到pair中。之后就可用常规方法进行排序了!
以上。
来源:CSDN
原文:https://blog.csdn.net/zengzeyu/article/details/79477087
版权声明:本文为博主原创文章,转载请附上博文链接!