jdepypere
jdepypere

Reputation: 3553

Write to file not visible before close; fflush(stdout) ineffective

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?

Upvotes: 2

Views: 1542

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

You're flushing stdout. You need to flush the file.

Change

fflush(stdout)

to

fflush(fp)

In terms of why the sleep() appears to impact whether contents are visible in the file: Without it present, you're writing to the file at a much higher rate, so you fill the in-memory buffer and flush to disk much faster. If you were patient enough, though, you'd see contents on-disk even with the sleep() present.

Upvotes: 8

Related Questions