Is it possible to read line at Nth index in a file in O(1) or less than O(n) time complexity ?

I want to read a large text file line by line, one way to read line at Nth index will be to go through all lower index lines but that will be taking too much time as the file is very large, so is there any way to reduce its time complexity or some way to make file reading faster. Language I am using is C

2/10/2020 1:54:04 PM

Gaurav Agrawal

2 Answers

New Answer


Random access to contents within a file is achievable with fseek(), but this is less feasible if the lines in your file are of variable length. This is because fseek() moves the file pointer according to the specified number of bytes, hence effectively "skipping" ahead, but not necessarily to the next line. If the number of bytes that your line contains is not constant, we won't know how many bytes to move the pointer ahead in order to read that particular line you need. https://code.sololearn.com/ciMidMF9QsIS/?ref=app


Hatsy Rei Thanks for the answer, unfortunately lines in my file are of variable length. I might can still use it by breaking my file into smaller files on basis of similiar length of lines.