tags:

views:

58

answers:

4

Hello,

I have a file with thousands of lines, each one representing a point of a line. The number of chars on each line is variable. Im plotting these lines, but i only want to plot every tenth line. I know i could just do something like:

for (int k = 0; k < 9; k++) {
    File.getline(buf, 1024);
}

but i was wondering if there was a way to do this without reading in all the lines in between. it just seems like a waste.

+3  A: 

In general, no. Unless your lines are fixed length or otherwise have some hints in them as to where the next lines are, you have no choice but to scan the file for newlines and throw away intervening characters.

Steven Schlansker
And by the line "The number of chars on each line is variable.", I'm going to guess that they're not fixed length. I'm just a bit psychic like that.
Stephen
Sure, I was just pointing out that if that constraint were relaxed it'd be a different story :)
Steven Schlansker
Ok. Well, no big deal. Im sure it wont be too slow anyways. Thanks!
Ben313
+2  A: 

If the lines are of fixed length, then you can use seekg(). Otherwise, no! Something has to go through the file finding newline characters.

Oli Charlesworth
+2  A: 

If you're going to be plotting from the same file a number of times, you can build an index telling where each line starts, and seek to the lines you want when you do the plotting. You need such an index to move ahead N lines (where N>1).

Even if you do build the index, don't be surprised if the code is just as fast without it (or, possibly, that it's faster with it, but by such a small margin it doesn't matter). Unless your lines are pretty long, chances are pretty good that (most of the time) you won't seek beyond the next chunk of data that would have been read from the disk anyway, so underneath it all, you'll end up reading through the file sequentially anyway.

Jerry Coffin
A: 

Yes. It's just a matter of calling File.ignore(MAX_INT, '\n').

MSalters