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;
}