I'm experimenting-learning and have written a small program that should periodically write text into a file.
$ cat test.c
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
int main() {
printf("First\n");
errno = 0;
FILE *f = fopen("test.file", "a");
int c = 0;
//int fd = 0;
if (f == NULL) {
printf("Something went wrong %d\n", errno);
return 1;
}
//fd = fileno(f);
printf("Starting loop\n");
while(1) {
c = fprintf(f, "12345\n");
//syncfs(fd);
printf("print %d, %d\n", c, errno);
sleep(10);
}
return 0;
}
The file test.file
already exists and is not empty. I compile test.c
with
$ gcc -Wall test.c
The problem is that the test.file
is not updated, although there does not seem to be any errors. Sample output
$ ./a.out
First
Starting loop
print 6, 0
print 6, 0
so it says that fprintf()
has written 6 bytes and errno
is zero which is correct.
I though it might be connected with filesystem cache (I'm actually trying to learn about filesystems, so this idea is probably completely insane), so I've added a call to syncfs()
to force writing data on disk. This part is commented out in the source code above. Still it doesn't work.
If I change the mode in fopen()
from a
to w
and rerun the program then test.file
is cleared, so I'm looking at the right file.
Why it doesn't get appended though?
I have gcc 5.4.0
on Ubuntu 16.04