seekg() function fails

ぃ、小莉子 提交于 2019-11-29 15:46:59

Rather than seeking back to the beginning and reading the first line twice, I think I'd approach things with something like:

std::ifstream file("filename");

std::string line;

std::getline(file, line);
process(line);

do { 
    process(line);
} while (getline(file, line));

At the moment, this assumes that process doesn't modify line (but if needed, it's easy enough to make an extra copy of it for the first call).

Edit: given the modified requirements in the edited answer, it sounds like the seek is really needed. That being the case, it's probably cleanest to clear the stream before proceeding:

std::getline(file, line);
process1(line);

file.seekg(0);
file.clear();

process2(file);

Ideally your code should look like this:

std::ifstream file("filename"); //no need of std::ios_base::in

if ( file ) //check if the file opened for reading, successfully
{
   std::string line;
   if ( !std::getline(file, line) )
   {
        std::cerr << "read error" << std::endl;
        return;
   }

   // process line

   if ( !file.seekg(0, ios::beg) )
   {
        std::cerr << "seek error" << std::endl;
        return;
   }

   while ( std::getline(file, line) )
   {
      // process line
   }
}
else
{
   std::cerr << "open error" << std::endl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!