Question

I'm new to C++, and have hit the first problem from which googling can't save me.

I have a set of data files with one record per line. Each of the files are sorted by a key, but some records are missing in some files. My plan is parse through these data line by line, extracting the data form the lowest record and adding missing data where aproriate.

The number of files used will change from one run of the code to the next, so it's important that the class/container holding the file streams can be variable-sized (ruling out arrays and, I think, vectors of pointers).

Here's a bare-bones version of what I have now, which won't compile as ifstreams have a deleted copy constructor (I thought move and c++11 might have me from this, apparently not). As I say, this is my first week of C++-ing, if there is an entirely different approach that is better suited to the problem I'm happy to hear it.

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;


class FileParser{
        ifstream file_stream;
    public:
        FileParser(string);
        string next();
};

FileParser::FileParser(string fname){
    file_stream.open(fname);
}

string FileParser::next(){
    string L;
    getline(file_stream, L);
    // do lots of parsing...
    return L;
}

int main(){
    vector<string> fnames = {"test1", "test2"};

    vector<FileParser> parsers;

    for(size_t i = 0; i < fnames.size(); ++i){
        FileParser p (fnames[i]);
        parsers.push_back( move(p) )
    }
    //loop through all files, find matching records, do stuff
    cout << parsers.size() << endl;
    return 0;
}
Was it helpful?

Solution

Well, one option is not to have a vector < FileParser > but rather a vector of smart pointers to your FileParser objects, so then copying the ifstream doesn't occur since there is only once instance of the ifstream and each smart pointer instance is just creating another reference to the ifstream.

vector< shared_ptr<ifstream> > v;
v.push_back( shared_ptr<ifstream>(new ifstream("test1") ) );

or better yet, 

v.push_back( make_shared<ifstream>("file1") );

Actually, in your case, you aren't making a shared_ptr < ifstream > but rather shared_ptr< FileParser >.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top