The point is this: there is a file (say 1000 lines) and I need to read line number 500. Is there a way to immediately refer to a specific line ???

  • If you know what byte it starts. - Harry
  • @Harry, that is, we allow lines of fixed length (size) and to get the 500th line length * 500 - Ljil
  • Well this is if those same 500 bytes include the end of line character (s). Then fseek() . - Akina
  • If the lines are of different lengths, then nothing, just read sequentially. But if storing the lines is not just in the file, but to organize the lines in the database, then it is possible. And even easier - to store 1000 lines in 1000 separate files. If you need line number 500, then just read the 500th file. :-) - pepsicoca1
  • In general, further iterations will lead to the creation of a database :) It is more reasonable to make 2 files, one with the row index, the other with the rows, in the first store a fixed structure with the offset of the beginning of the line and its length, or the end of the line offset - as more convenient .. - NewView

1 answer 1

If the lines are of fixed length, then you can calculate the position from which this line starts (roughly speaking, len*500 ), then set the file pointer to the desired position ( fseek(f,pos,SEEK_SET) function fseek(f,pos,SEEK_SET) , since you have C) and count what you need.

I would open the file as binary.

Well, if all the strings are different and you do not have information about their sizes — to calculate the position of the beginning of the N-th row, then only by reading a row to the required row.