rebatoma
rebatoma

Reputation: 742

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.

Upvotes: 0

Views: 1905

Answers (2)

boeing777
boeing777

Reputation: 9

It seems there are no specific C++ functions, like "seekline", for your needs, and I see two ways to solve this task:

  1. Preliminary you can expand every line in textfile with spaces to reach a constant length L. Than, to seek required line N, just use seekg with L * N offset.
  2. This method is more complicated. You can create an auxiliary binary file, every byte of it will keep length of every line of source file. This auxiliary file is a kind of database. Next, you have to load this binary file into array in your program within initialization phase. The offset of a required line in textfile should be calculated as sum of first N array's elements. Of course, it's necessary to update an auxiliary file and source file simultaneously.

The first case is more efficient if a textfile is loyal for it's size requirements. The second case brings best perfomance for long textfile and rare edit operations.

Upvotes: 0

Arthur Golubev 1985
Arthur Golubev 1985

Reputation: 677

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.

Upvotes: 3

Related Questions