Search code examples
c++ifstreamgetline

C++ getline() after clear()


First, I'm sorry but I don't speak english very well. My problem is that I want my stream go back begining of the file. So, i apply the clear() method upon my stream object, but after this, getline() always return 0 (false). I don't find the solution. Somebody has an idea about this problem? So, this is my code:

void Tools::tokenizeAll(string filename, string separator){
  char str[LINESIZE] = {0};
  int lineNumber = 0, j = 0;

  ifstream stream;
  stream.open(filename.c_str(), std::ifstream::in);
  if(stream){
    while(stream.getline(str, LINESIZE)){
      lineNumber++;
    }

    //allocation dynamique du tableau à deux dimensions
    string** elementsTable = NULL;
    elementsTable = new string*[lineNumber];
    for( int i = 0 ; i < lineNumber ; i++ ) elementsTable[i] = new string[4];

    std::cout << " good()=" << stream.good() << endl;
    std::cout << " eof()=" << stream.eof() << endl;
    std::cout << " fail()=" << stream.fail() << endl;
    std::cout << " bad()=" << stream.bad() << endl;
    cout << endl;

    stream.clear();

    std::cout << " good()=" << stream.good() << endl;
    std::cout << " eof()=" << stream.eof() << endl;
    std::cout << " fail()=" << stream.fail() << endl;
    std::cout << " bad()=" << stream.bad() << endl;
    cout << endl;

    cout << stream.getline(str, LINESIZE) << endl;//return 0


  }
  else cout << "ERREUR: Impossible d'ouvrir le fichier en lecture." << endl;
}

Thank you very much (and thank you to warn me about my english errors ;) )


Solution

  • Calling clear() only resets the error flags. To "rewind" the stream to the beginning, you'll also need to use seekg:

    stream.seekg(0, std::ios::beg)
    

    Note that this operation can fail, too, so you might want to check for errors.