Your file has a first line that has 18 characters, a second line with the same number of characters, and a third one with one less (17) number of characters.
In case you have a four line in which the name for example makes the number of characters different, they should be appended to the file without any other structure.
Lines are delimited by \n
characters, that can appear at any point, so second line starts as soon as just behind the first appearance of the \n
char.
For this reason, you don't know the precise position where each line begins, and so you cannot know the exact position where each line begins, as the position of each line is (n + 1)
bytes forward from twhere the previous line started, where n
is the number of characters you put in the previous line, plus one (for the new line character).
You need an index, which is a file that allows you to get, on a fixed length record, to store the starting positions of each line in the data file. In this way, to read line i
, you access the index at position (record_index_size * i)
, and get the position of the starting point of line i
. Then you go to the data file, and position your file pointer to the value obtained from the las calculation, and read that with, for example fgets(3)
.
To build the index, you need to call ftell()
right before each call to fgets()
, because the call to fgets()
will move the pointer, and so the position obtained will not be correct. Try to write the position in a fixed length format, e.g. binary form, with:
write(ix_fd, position, sizeof position);
so the position of line i
, can be calculated by reading from index at position i * sizeof position
.