C++文件目錄操作---opencv和boost例子

通常需要對文件夾進行操作,在不使用qt的庫的情況下,還可以利用opencv和boost進行。這樣方便程序的移植

(當然標準c/c++應該也有相應的操作)

經測試,opebcv和boost拿到的文件夾下面的文件名,是亂序的,需要根據文件名進行排序

一、opencv 2操作:

  主要參照:http://blog.csdn.net/holybin/article/details/25786727

 

#include <iostream>
#include <vector>
#include <opencv2/contrib/contrib.hpp>

using namespace std;
using namespace cv;

int main()
{
    string dir_path = "/home/wk/DataSet/Phone/vins2/cam0/";
    Directory dir;
    vector<string> filenames = dir.GetListFiles(dir_path, "*", false);
    std::sort(filenames.begin(),filenames.end(),less<string>()); //升序排列,降序排列的話是greater<>()    很重要,根據文件名進行排序
    cout << filenames.size() << endl ;
    for(int i = 0; i< filenames.size(); i++)
    {
        cout<< filenames[i].substr(0,filenames[i].size()-4)<< endl;  //這裏-4,是去掉擴展名
    }
    return 0;
}

opencv3的操作見:

https://blog.csdn.net/qq_31261509/article/details/79460639

 

 

 

 

二、boost操作:

boost模塊還沒有找到如何給文件名進行排序的方法

 

#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;


int main()
{
    const boost::filesystem::path path("/");
    boost::filesystem::directory_iterator end;
    boost::filesystem::directory_iterator iter_file(path);

    for(iter_file ; iter_file != end ; iter_file++)
    {
        cout<<*iter_file<<endl;

    }
    //-- 注意這裏訪問是隨機,並不是從第一個文件到最後一個,需要自己對結果進行重新排列。把結果保存到vector,使用sort進行排序
    return 0;
}

注意,boost::filesystem並不是直接包含頭文件就可以解決的,需要添加庫依賴。

 

在CMakeLists.txt中添加:

 target_link_libraries(boostfiletest "/usr/local/lib/libboost_system.so" "/usr/local/lib/libboost_filesystem.so" )

經測試,不需要絕對路徑也可以,因爲在系統制定的庫目錄中,

 

target_link_libraries(boostfiletest "libboost_system.so" "ibboost_filesystem.so" )

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章