Reading line X to line Y from a file in C ++
I have a relatively simple question. Let's say I have a file, but I only want to access line X of the file to line Y, what is the easiest way to do this?
I know I can read the lines one at a time, keeping the count until I get to the lines I really want, but is there a more elegant solution?
Thanks.
a source to share
In C ++, no, not really (well, in some language I'm familiar with, really).
You need to start at the beginning of the file so you can see where line X starts (unless it's a fixed length file, but that's unlikely for text).
Likewise, you must do this until you find the last line of interest.
You can read characters instead of lines if you're afraid of buffer overflow exploits, or can read in a fixed size block and count newlines for speed, but it all comes down to reading and checking each character (explicitly by your code, or language libraries implicitly) for line counts ...
a source to share
With C or C ++, there are some functions that you can use to skip a certain number of bytes in a file (fseek to stdio and seekp with istreams and ostreams). However, you cannot specify a given number of lines, since each line can have a variable number of characters and therefore it is not possible to calculate the correct offset. A file is not some kind of array in which each line occupies a "line": you rather need to see it as a contiguous space of memory (not to mention hardware here ...)
a source to share