I am reading a file in a while loop from start to end:
FILE *file;
file = fopen(path_to_file), "r");
char *line = NULL;
size_t len = 0;
while (getline(&line, &len, file) > 0) {
delete_line_from_file(line);
}
fclose(file);
The function delete_line_from_file()
removes the line passed to it from the file. It reads in the whole file via open(fd, O_RDONLY | O_CLOEXEC)
+ read()
+ close()
, then removes the line from the buffer and writes the whole buffer to the same file via open(fd, O_WRONLY | O_TRUNC | O_CLOEXEC)
+ write()
+ close()
. The read()
is locked in an advisory read-lock via struct flock lk
and the write()
is locked in an advisory write-lock.
When I read the file there are lines that get missed which has something to do with me reading the file from start to finish in one loop while writing to it. If I read in the whole file and go through the buffer line-by-line no lines get missed. (This is my preferred solution so far.) There are also no mistakes made when truncating and writing the file. The missed lines are still in the file after the loop finishes.
Can I make sure that my while-loop does not miss a line and cleanly empties the file? The file needs to be emptied line-by-line. It cannot be just truncated.
Here is one possible solution I had in mind. Mirror the file via fstat(file &fbuf)
and check it's size with if (fbuf.st_size !=0) fseek(file, 0, SEEK_SET);
but that seems inefficient.