0

The source code of program_1 is as follows.

/* program_1.c */

#include <stdio.h>

int main(void)
{
FILE *ofp;

ofp = fopen("myfile", "w");

fprintf(ofp, "test");

getchar();

fclose(ofp);

getchar();

return 0;

}

The terminal running one program_1 and another terminal for viewing the contents of myfile are first displayed.

  1. If I check the contents of myfile while running program_1, string "test" is not printed.

  2. However, if I input the enter key once while running program_1 and check the contents of myfile, I can see that the "test" string has been printed.

question : Why is this happening?

y J.
  • 131
  • 4
  • 2
    Take a look at https://stackoverflow.com/questions/20267244/why-fprintf-doesnt-write-directly-into-the-file-unless-fflush-is-used. Basically fprintf buffers (or caches) for performance - in your case only writing out when the fclose is hit. – racraman Nov 10 '21 at 07:38
  • 1
    You could use fflush() after the fprintf. – Klas-Kenny Nov 10 '21 at 07:39

0 Answers0