read more files using only one std::ifstream file

Today meets a bug, when read more than one files using only one std::ifstream object. possible code as following:

std::ifstream infile

infile.open(a)
if (infile.bad()) {
   std::cerr << "read failed" << std::endl;  
}

std::string line = "";
while (std::getline(infile, line), infile.good()) {
   std::cout << line << std::endl;
}

infile.close();

//next ,continue read b file
infile.open(b);

if (infile.bad()) {
  std::cerr << "read failed" << std::endl;
}
line = "";
while (std::getline(infile, line), infile.good()) {
   std::cout << line << std::endl;
}

but, file b can not be read out!

OK, the bug is :after read out of file a, the object "infile"'s state is error, because of reading nothing out finally for file a.

only use "infile.close()" is not enough, it also needs clear; so ,fix it as follows:

infile.close()
infile.clear();

then bug fixed.

reminding~

posted @ 2013-01-28 22:09  Crafet.36.77  阅读(203)  评论(0)    收藏  举报