using one ifstream variable for reading several files

shookees picture shookees · Nov 15, 2011 · Viewed 17.7k times · Source

Possible Duplicate:
C++ can I reuse fstream to open and write multiple files?

why is it not possible to use one ifstream variable for opening one file, reading it, then closing it and, after that, opening another file, reading and closing, etc? How would that look in code (let's just say each file has an integer inside):

int k, l;  
ifstream input1;  
input1.open("File1.txt");  
input1 >> k;  
input1.close();  
input1.open("File2.txt");  
input1 >> l;  
input1.close(); 

the only way I solved the problem was creating another ifstream variable.

Answer

SoapBox picture SoapBox · Nov 15, 2011

You can use the same variable, you need to call .clear() to clear the object's flags before you reuse it:

int k,l;
ifstream input1;  
input1.open("File1.txt");  
input1 >> k;  
input1.close();  
input1.clear();
input1.open("File2.txt");  
input1 >> l;  
input1.close();
input1.clear();

But I recommend instead you don't reuse them. If you don't want to have more than one variable around at once, you can keep each one in its own scope:

int k,l;

{
    std::ifstream input1("File1.txt");  
    input1 >> k;
}
{
    std::ifstream input1("File2.txt");  
    input1 >> l;  
}