使用Boost读取多个文件C ++ [英] Read multiple files C++ using Boost

查看:141
本文介绍了使用Boost读取多个文件C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Boost库读取多个文件的内容. 我已经成功列出了文件夹中的所有文件,但是我一直试图读取它们...

I am trying to read the content of multiple files with the Boost library. I have succeeded to list all the files in a folder but I am stuck at trying to read them...

#include <iostream>
#include "boost/filesystem.hpp"

using namespace std;
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
    // list all files in current directory.
    // You could put any file path in here, e.g. "/home/me/mwah" to list that
    // directory
    path p("/home/baptiste/Bureau");

    directory_iterator end_itr;

    // cycle through the directory
    for (directory_iterator itr(p); itr != end_itr; ++itr)
    {
        // If it's not a directory, list it. If you want to list directories too,
        // just remove this check.
        if (is_regular_file(itr->path())) 
        {
            // assign current file name to current_file and echo it out to the
            // console.
            string current_file = itr->path().string();
            cout << current_file << endl;
        }
    }
}

推荐答案

使用ifstream打开文件,然后使用getline()逐行将其内容读取到string中:

Use an ifstream to open the file, and getline() to read its contents into a string line by line:

#include <fstream>
#include <string>

std::string line;
std::ifstream ifs(itr->path().string().c_str());
if (ifs) {
    while (std::getline(ifs, line)) {
        // Process line
    }
}
else {
    std::cerr << "Couldn't open " << itr->path().string() << " for reading\n";
}

这篇关于使用Boost读取多个文件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆