I have a program that looks like this. I need to consistently write something into a text file but I cannot predetermine when the program is going to end. So I force quit the program.
FILE *f = fopen("text.txt", "w");
while (1) {
fprintf(f, "something");
sleep(1000);
}
The problem is that the text file would be empty. Can anyone give me some suggestions?
I am using XCode to do the job.
Use
fflush(f)afterfprintf(f)otherwise the data you printed is still in the stream buffers in stdio and hasn’t yet reached the filesystem.Note that doing this very often may dramatically reduce your performance.