Boat
Boat

Reputation: 529

Read multiple files C++ using 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;
        }
    }
}

Upvotes: 2

Views: 1671

Answers (3)

jotik
jotik

Reputation: 17900

You can use the C++ standard library to read the file.

The most simple way to read a file line-by-line would be something like

#include <fstream>
#include <string>

// ... and put this inside your loop:

if (std::ifstream inFile(current_file.c_str())) {
    std::string line;
    while (std::getline(inFile, line)) {
         // Process line
    }
}

Upvotes: 1

Boat
Boat

Reputation: 529

For those who want the entire code .

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


using namespace std;
using namespace boost::filesystem;

int main (int argc, char *argv[])
{

path p ("/home/baptiste/workspace/booost");

directory_iterator end_itr;


for (directory_iterator itr(p); itr != end_itr; ++itr)
{

    if (is_regular_file(itr->path())) {

        string current_file = itr->path().string();
        cout << current_file << endl; }

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

}

}

Upvotes: 0

user325117
user325117

Reputation:

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";
}

Upvotes: 2

Related Questions