Nikolai Josuttis on page 547 of his book, The C ++ Standard Library, says the following regarding the code below:
Note that after the processing of a file, clear() must be called to clear the state flags that are set at end-of-file. This is required because the stream object is used for multiple files. The member function open() does not clear the state flags. open() never clears any state flags. Thus, if a stream was not in a good state, after closing and reopening it you still have to call clear() to get to a good state. This is also the case, if you open a different file.
#include <fstream>
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
ifstream file;
for (int i=1; i<argc; ++i) {
file.open(argv[i]);
char c;
while (file.get(c)) {
cout.put(c);
}
file.clear();
file.close();
}
}
My code below works without problems in VS2010. Please note that after creating the file "data.txt" it reads twice without clearing the flags of the input stream.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream out("data.txt");
out << "Line 1" << '\n' << "Line 2" << '\n' << "Line 3" << '\n' << "Line 4" << '\n';
out.close();
std::ifstream in("data.txt");
std::string s;
while( std::getline(in, s) ) std::cout << s << '\n';
std::cout << '\n';
std::cout << std::boolalpha << "ifstream.eof() before close - " << in.eof() << '\n';
in.close();
std::cout << std::boolalpha << "ifstream.eof() after close - " << in.eof() << '\n';
in.open("data.txt");
std::cout << std::boolalpha << "ifstream.good() after open - " << in.good() << '\n';
std::cout << '\n';
while( std::getline(in, s) ) std::cout << s << '\n';
std::cout << '\n';
}
Ouput

source
share