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" )

 

 

 

 

 

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