I'm having some issues with writing to a file whilst also having a delay in a while loop. Here's a snippet:
void main(int){
FILE * fp = NULL;
sprintf(filename, "log%i.msg", SET_ID);
fp = fopen(filename, "w+");
fprintf(fp, "File started\n");
while(1){
fprintf(fp, "%i %u %s\n", someInt, someUnsigned, someString);
fflush(stdout);
sleep(5); // Commenting out this line will work
}
fclose(fp);
return 1;
}
Running the code gives me an output file of 0 bytes with nothing in it whilst the sleep is taking effect, although the file does have the expected content when my code finishes running. However, when I remove the sleep(5);
line, it does print correctly. I've searched about this already, but what I've found is that it needs to be flushed, but I do this (though apparently incorrectly). What am I doing wrong?