0

Is there a fast way to get a line from a text file by the line number? If I wanted only line 20 is there anything that will allow me to do something like get line 20? I know getline(in, line) reads in each line one at a time but I rather not call getline 20 times to get the 20th line.

Thanks!

user3194708
  • 87
  • 1
  • 10

2 Answers2

1

No, you have to use a loop that will advance to the next line twenty times.

The reason it is not possible to do what you want is the way the file is structured: It's a sequence of bytes, and a new line is just another byte (or a sequence of two bytes, by the Windows convention).

01d55
  • 1,872
  • 13
  • 22
1

No, there is no fast and magical method.

Background
Text file records are variable length. Each text line may vary in the number of characters. Fixed records are easy since their length is known.

To find the Nth record, you have to find the beginnings or endings of the text records. This is often performed by searching for a newline character. Still tedious.

Converting to Random Access
If the data is requested many times, a map or dictionary of the record line number and its position would be handy. Use the line number, retrieve the file postion, then set the file pointer to the given position.

Memory mapped file
If there is enough memory, the file could be read and stored in memory.

However, one still has to search for the newlines and count them to find line X.

Summary
There is no fast method to find the start of a text line in a file, the first time. In any case, the text must be searched for the newlines and the newlines counted.

There are methods to speed up the process, but those involve reading the file one or more times. The mapping of line numbers to file positions is fast but requires an initial scan. Loading the file into memory (memory mapping) requires reading the file into memory (first read) then searching the memory; also, the OS may only load portions of file that are requested and not the entire file.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154