基于Boost库的C++文件遍历

来源:互联网 发布:js难学吗 编辑:程序博客网 时间:2024/06/07 01:33

现在文件遍历操作一般都是通过Python,Java之类的语言实现。以至于要用C++实现的时候竟然不知道怎么做了。于是,百般查资料,找到Boost库,提供文件遍历,特提供代码,测试通过。

  1. 首先安装boost,linux直接使用命令安装即可。或者使用下载的boost库里面的脚本直行至即可。下边讨论windows版本。下载之后我们可以得到如下的目录结构,
  2. 执行目录下bootstrap.bat得到bjam.exe,点击进行库编译。大约需要10多分钟。
  3. 配置vs,我用的是vs comunnity 2015,在建立的工程上右击选取属性。导入头文件。(附加包含目录)
  4. 导入编译出来的库文件。(附加库目录)
  5. 完成boost库的安装
  6. 下边是实际代码,首先FileIter.h文件
    #ifndef __FILEITER__H_#define __FILEITER__H_#include <iostream>#include <boost/filesystem.hpp>using namespace std;using namespace boost::filesystem;class FileIter {private:string path;vector<string> data;public:FileIter(string path);void walk();void walk(string path);void walk(boost::filesystem::path p);vector<string> get_vector();};#endif
    FileIter.cpp
    #include "FileIter.h"FileIter::FileIter(string path) {this->path = path;}void FileIter::walk() {walk(path);}void FileIter::walk(string path) {auto p = boost::filesystem::path(path);walk(p);}void FileIter::walk(boost::filesystem::path p) {try {if (exists(p)) {if (is_regular_file(p)) {//cout << p << " size is " << file_size(p) << '\n';data.push_back(p.string());}else if (is_directory(p)) {//cout << p << " is a directory containing:\n";for (directory_entry& x : directory_iterator(p)) {walk(x.path());}}else {cout << p << " exists, but is not a regular file or directory\n";}}else {cout << p << " does not exist\n";}}catch (const filesystem_error& ex) {cout << ex.what() << '\n';}}vector<string> FileIter::get_vector() {return data;}
    测试主函数
    #include<iostream>#include"FileIter.h"using namespace std;int main() {cout << "hello" << endl;    FileIter p("D:\\document");    p.walk();    vector<string> data = p.get_vector();    for (auto temp : data) {        cout << temp << endl;    }return 0;}

1 0
原创粉丝点击