tags:

views:

81

answers:

3

Hiya.

I'm using std::getline to read lines from a file, how can I move forward a few lines? do I have to use getline the number of lines I want to skip?

thanks!

+3  A: 

Yes use std::getline unless you know the location of the newlines.

If for some strange reason you happen to know the location of where the newlines appear then you can use ifstream::seekg first.

You can read in other ways such as ifstream::read but std::getline is probably the easiest and most clear solution.

Brian R. Bondy
+1 -- or at least will be +1 in 13 mins when I have votes...
Billy ONeal
+1 -- actual this time :)
Billy ONeal
@Billy: Actually your tardiness gave me 10 extra rep since I was already at max cap until 10 min ago.
Brian R. Bondy
@Brian R. Bondy: LOL! I have yet to bump my head into said cap.
Billy ONeal
+3  A: 

do I have to use getline the number of lines I want to skip?
No, but it's probably going to be the clearest solution to those reading your code. If the number of lines you're skipping is large, you can improve performance by reading large blocks and counting newlines in each block, stopping and repositioning the file to the last newline's location. But unless you are having performance problems, I'd just put getline in a loop for the number of lines you want to skip.

Billy ONeal
Counting newlines is sorta what a looped `getline` would do, right?
GMan
good to know, great information, thanks!!!!
ufk
@GMan - Save the Unicorns: Yes, but you can use larger blocks and shift forward a larger distance if you know n is large (i.e. counting more than one newline in a buffer block)
Billy ONeal
what if I'll load all the file to memory and parse it with regular expressions ? the file is less then 1MB.
ufk
@ufk: Benchmark it. I'm unsure myself.
Billy ONeal
ok guess we pretty much say the same thing... +1.
Brian R. Bondy
+2  A: 

For what it's worth:

void skip_lines(std::istream& pStream, size_t pLines)
{
    std::string s;
    for (; pLines; --pLines)
        std::getline(pStream, s);
}
GMan