Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using one ifstream variable for reading several files [duplicate]

Tags:

c++

ifstream

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.

like image 609
psukys Avatar asked Nov 15 '11 13:11

psukys


1 Answers

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;  
}
like image 121
SoapBox Avatar answered Oct 30 '22 13:10

SoapBox