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

只愿长相守 提交于 2019-12-24 07:39:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24101566/write-to-file-not-visible-before-close-fflushstdout-ineffective

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!