I want to read a specific line from a text file without reading the whole file line by line. For Example, if I have 10 lines in a text file and I have to read 6th line, I will not read the first 5 lines but will directly read the 6th one. Can anyone help me??
-
3If the length of the line is not fixed it is impossible(If the file does not exist for the index). – BLUEPIXY May 17 '15 at 15:17
-
3There's really no way to do it, since you can't say what position in the file the line starts on in a normal text file. You simply have to loop, and read (and discard) all lines before the wanted one. – Some programmer dude May 17 '15 at 15:17
-
6If a "line" has a fixed length, you can use `fseek`. Otherwise, there's no way to do that. – user4520 May 17 '15 at 15:19
2 Answers
This question is answered here
Quoting from above,
Unless you know something more about the file, you can't access specific lines at random. New lines are delimited by the presence of line end characters and they can, in general, occur anywhere. Text files do not come with a map or index that would allow you to skip to the nth line.
If you knew that, say, every line in the file was the same length, then you could use random access to jump to a particular line. Without extra knowledge of this sort you simply have no choice but to iterate through the entire file until you reach your desired line.
Credits : Quoted answered was by David Heffernan
You could 'index' the file. Please note that this is only worth the effort if your text file:
- is big
- is frequently read and rarely written
The easiest (and probably most efficient) way is to use a database engine. Just store your file in a table, one row for each line.
Alternatively, you could make your own indexing mechanism. Basically, this means:
- create a new file (the index)
- scan the entire text file once, storing the offset of each line in the index file
- repeat the above each time the text file changes
Finding line n in the text file requires two seeks:
- read the nth offset from the index
- read a line from the text file, starting at the offset found in the index

- 10,563
- 1
- 26
- 45