mardi 1 décembre 2015

C++ Vector of pointers to files

I am currently trying to access pointers to files from vector. The problem I am facing and which I can't alone solve is that i am re-writing already stored pointers in vector with the last created (or at least it seems so). So if I try access them, only the last is available. Maybe there is simple solution to this that I just can't see, but I have spend already three days trying to find what I am doing wrong (I have completely rewritten the code from scratch twice).

int cnt = 0;
vector<AbstractInput*> abstractFiles;
while (cnt < 10) {
    string path = "D:/tempSort_" + to_string(cnt) + ".txt";
    ofstream fileOutput(path);
    if (!fileOutput)
    {
        // todo error 
        exit(1);
    }
    AbstractOutput* tmp = new FileOutput(fileOutput, kernel);
    tmp->WriteLine(to_string(cnt) + " zkouska");
    tmp->WriteLine(to_string(cnt) + " zkouska2");
    tmp->WriteLine(to_string(cnt) + " zkouska3");
    tmp->Close();
    delete(tmp);

    ifstream fileInput(path);
    if (!fileInput)
    {
        exit(1);
    }       

    abstractFiles.push_back(&(FileInput(fileInput, kernel)));

    output->WriteLine("CNT = " + to_string(cnt));
    for (AbstractInput* it : abstractFiles)
    {
        bool succes;
        output->WriteLine((it)->ReadLine(succes));
    }       


    cnt++;

} 

FileInput:

using namespace std;

class FileInput : public AbstractInput
{
    using AbstractInput::AbstractInput;


private:
    ifstream& inputFile;
    bool closed;

public:
    FileInput::FileInput(ifstream& inputFile, Kernel* kernel) : 

    AbstractInput(kernel), inputFile{ inputFile }, closed(false)
    {   

    }

    int FileInput::Close()
    {
        inputFile.close();
        closed = true;
        return 0;
    }

    bool FileInput::HasNext()
    {
        return !closed;
    }
    string FileInput::Read()
    {
        return GetKernel()->ReadFromKeyboard();
    }
    string FileInput::ReadLine(bool& success)
    {
        string line = GetKernel()->ReadLineFromFile(inputFile, success);

        closed = !success;
        return line;    
    }

};

Kernel functions:

string Kernel::ReadLine(istream& stream, bool& success)
{
    string line;
    if (getline(stream, line))
    {
        success = true;
        return line;
    }
    success = false;
    return "";
}

string Kernel::ReadLineFromFile(ifstream& stream, bool& success)
{   
    return ReadLine(stream, success);
}

EDIT: Added whole code + FileInput class EDIT2: Added Kernel functions

Aucun commentaire:

Enregistrer un commentaire