Using a single ifstream variable to read multiple files

Possible duplicate:
C ++ is it possible to reuse fstream to open and write multiple files?

why is it impossible to use one ifstream variable to open one file, read it, then close it and then open another file, read and close, etc.? How would it look in the code (just say that 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 to solve this problem is to create another ifstream variable.

+7
source share
4 answers

You can use the same variable, you need to call .clear() to clear the flags of the objects before reusing them:

 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 that you do not reuse them instead. If you do not want to have several variables at once, you can save them in your area:

 int k,l; { std::ifstream input1("File1.txt"); input1 >> k; } { std::ifstream input1("File2.txt"); input1 >> l; } 
+12
source

Call clear() after close() on an ifstream object

+4
source

The source code of the question works well:

 #include <fstream> using namespace std; int main() { int k, l; ifstream input1; input1.open("file1.txt"); input1 >> k; input1.close(); input1.open("file2.txt"); input1 >> l; input1.close(); } 

Note that from C ++ 0X (C ++ 11) there is no need to call basic_ifstream::clear() , because the standard indicates (see C ++ 0x / 27.9.1.9) a successful basic_ifstream::open() should call basic_ifstream::clear() .

+2
source

While it is possible to do what you suggest (although you may need to clear the stream error flags if the extraction failed), it is not very elegant. In C ++, you should be able to create new objects when you need them, and discard them when you are done. Perhaps a more systematic way of writing this code is in the local loop area:

 int result; while (true) { std::ifstream infile(get_random_file_name()); if (infile >> n) { break; } // "infile" gets destroyed at the end of the scope } std::cout << "We found a good file, and it contains: " << n << std::endl; 

You can, of course, replace the loop logic with something else that is more suitable for your situation. For example, according to the Zero-One-Many rule, you might have a container somewhere containing your candidate file names; or you can iterate over command line arguments.

+1
source

All Articles