Search code examples
c++ifstreamseekg

ifstream how to start read line from a particular line using c++


I'm using ifstream to parse a file in a c++ code. I'm not able using seekg() and tellg() to jump in a particular line of the code.

In particular I would like to read a line, with method getLine, from a particular position of the file. Position saved in the previously iteration.


Solution

  • You just have to skip required number of lines. The best way to do it is ignoring strings with std::istream::ignore

    for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
        if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){
            //just skipping the line
        } else {
            // todo: handle the error
        }
    }
    

    The first argument is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit.

    You should use is instead of std::getline due to better performance.