I'm getting some weird results, while trying to write data to files in C.<br/>
I thought that fclose()
closes the *FILE
and flushes
the data from its buffer to the file.<br/>
But for some reason it only flushes the data in my program sometimes and it doesn't do it other times.
For example: I would run this code, and in my file I can see the two strings. (Perfect, exactly what I want)
But then when I run the code the next 4 times it doesn't change anything in my file. And then when I run it another time, suddenly the 10 extra strings appear (8 from the last times I ran the program and the 2 from now)
(This 4 times is just an example, sometimes it's 5, 8, 10, or even just 2 times before I see the output appear)
I really don't understand this? Shouldn't the data be visible after every time I run the program? Where is this buffer even saved between the different times I run the program, because the program finishes every time, so the memory gets released, right?
(By the way I also tried fflush(fd)
before and after fclose(), but that didn't solve the problem)
#include <stdio.h>
int main(int argc, char const *argv[]) {
FILE * fd;
fd = fopen("test_file.txt", "a");
fprintf(fd, "String 1\n");
fprintf(fd, "String 2\n");
fclose(fd);
return 0;
}
if (fclose(fd)) perror("fclose");
. When there is no error,fclose()
includes the equivalent of afflush()
: see C11 7.21.5.1. – Ampfprintf()
statements may not actually be written to the file untilfclose()
is called, and thatfclose()
can fail after all your other calls appeared to succeed because the data was buffered and not actually written untilfclose()
flushed it. If your disk gets full or other problems happen, all those previous "successful"fwrite()
calls can be wiped out. – Hamburgerfclose
also callingfclose
is not ensuring that data is already on the disk. see my answer below. thank you. – Morgansteintail -f test_file.txt
in another terminal, I get the extra lines every single time. I agree with others the problem is likely in what you use to view the file. – Michaels