1. 程式人生 > >讀取資料夾下同型別檔案的檔名並排序(例項)

讀取資料夾下同型別檔案的檔名並排序(例項)

前言

工作過程中需要讀取指定資料夾下同型別檔案,並根據檔名最後幾位數字進行排序。當檔名全為數字時,直接根據數字就可進行排序,但是,如果檔名是含有非數字型變數(如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中。之後就可用常規方法進行排序了!


以上。