cfile-iofopenrewind

Why rewind() followed by fscanf() do not reflect changes made on disk?


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).

How do I fix the above code without fopen and fclose every time?


Solution

  • You can't. The gedit program does not change the file. That's simply not how it works. So you will not see any change to the file.

    The changes gedit makes 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 that gedit made.