I am repeatedly reading a previously-opened file using fscanf and rewind:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
void read_opened_file(FILE *file, int *value)
{
errno = 0;
fscanf(file, "%d", value);
if (errno != 0) perror("fscanf error");
errno = 0;
rewind(file);
if (errno != 0) perror("rewind error");
}
int main(int argc, char* argv[])
{
int value = 0;
FILE *file = fopen(argv[1], "r");
errno = 0;
if (setvbuf(file, NULL, _IONBF, 0) != 0) perror("setvbuf error");
for (int i = 0; i < 10; ++i)
{
read_opened_file(file, &value);
printf("value = %d\n", value); fflush(stdout);
sleep(1);
}
fclose(file);
return 0;
}
However, any changes made to the file on disk behind the scenes by gedit, echo >, cp are not reflected: the function keeps reporting the first (cached?) value read (and errno is not set).
- When I
setvbuf(file, NULL, _IONBUF, 0);as suggested here, changes made bycpandecho >are reflected, but changes made bygeditare still not reflected. - When I use
fopenandfcloseevery loop iteration everything is as expected.
How do I fix the above code without fopen and fclose every time?
You can't. The
geditprogram does not change the file. That's simply not how it works. So you will not see any change to the file.The changes
geditmakes are done by replacing the old file with a new file. You must close the old file and open the new file to see the changes thatgeditmade.