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.

0


a source to share


5 answers


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 ...

+5


a source


You can use istream :: ignore () to avoid buffering unnecessary input.



bool skip_lines(std::istream &is, std::streamsize n)
{
  while(is.good() && n--) {
     is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  }

  return is.good();
}

      

+4


a source


Search \ n X times, start "reading" (whatever processing that entails) until you reach YX \ n or EOF. Suppose unix style newlines.

+2


a source


Since you must provide trailing line characters within each line to be able to count the line, you still need to iterate over the file. The only optimization I can think of is not reading the file line by line, but the buffer, and then iterating over the line count.

+2


a source


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 ...)

0


a source







All Articles