How to avoid if fstream opens a directory (infinite loop)?

If the filename below is a directory, then the following loop goes to infinite.

std::ifstream in;, std::ifstream::in);
if( return;
if (in.bad()) return;
if (in.good()) {
int i;
while (!in.eof()) {
std::string sLine;
std::getline(in, sLine);
std::cout << i++ << "\t" << sLine << std::endl;
Just don't use while (!in.eof()). Check the result of getline() instead: while(getline(in, sLine) { ...
Topic archived. No new replies allowed.