lundi 29 juin 2015

One ifstream variable, multiple files c++ (programming help)

Can you use one ifstream variable to have multiple files?

I have a program that successfully reads all the files in a directory. However, while reading, the program only reads the first file, and puts all its lines into a vector. All the other files are not read.

I tried to use the clear() function but it still doesn't work. Help please!

Here is the code:

//This part prints all the files and works fine.

    for (unsigned int i = 0;i < files.size();i++) {
            cout << files[i] << endl;
    }



int iteratora = -1;

string line;//variable for holding the characters in one line
vector<string> programFile = vector<string> ();
//ignore this line vector<string> librariesIncluded;



for (unsigned int i = 0; i < files.size();i++ ){//for loop start

    iteratora++;
    string filename1 = files[iteratora];

        cout << "\n" << filename1 << ".\n";
        cout << "Iterator: " << iteratora << ".\n";

    programFile.clear();
    fstream afile (filename1);//(filename1);


    string line;//variable for holding the characters in one line



    if (afile.is_open())
    {
        while ( getline (afile,line) )
        {
            //cout << line << '\n';
            if (line != ""){
            programFile.push_back(line);
            line = "";
            }

        }
        afile.close();
    }

    afile.clear();

   print_vector(programFile);//used to know what is in the file
    /*

      do stuff with 'programFile'


    */  

}//loop end

print_vector() definition

void print_vector(const vector<string> &v)
{
    for (auto i = v.begin(); i != v.end(); ++i)
    {
        cout << "\n";
        std::cout << *i;
        cout << "\n";
    }
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire