0

I have this code. I want to update the writes immediately to log file before closing the file (because my program might get hang and I have to exit it by ctrl+c so fclose would never be called). The code is:

1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 int main()
  5 {
  6         FILE* fp = fopen("test.log","wb");
  7         if (fp == NULL)
  8         {
  9                 printf("file not found\n");
 10                 exit(1);
 11         }
 12 
 13         fprintf(fp, "today is %d day\n",420);
 14         fflush(fp);
 15         getchar();
 16         fclose(fp);
 17 
 18         return 0;
 19 }

but even though I force it to halt at line 15 so that I can view the log file from another console, I do not see any output written when opening the file. I am not sure why it is not working as expected.

Need some help here.

Thanks.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by nezachem
0

I have this code. I want to update the writes immediately to log file before closing the file (because my program might get hang and I have to exit it by ctrl+c so fclose would never be called). The code is:
...
but even though I force it to halt at line 15 so that I can view the log file from another console, I do not see any output written when opening the file. I am not sure why it is not working as expected.

Need some help here.

Thanks.

fflush ejects unwritten data from the stdio buffers, and causes an underlying write system call. The further events in the data life cycle are in the hands of OS and beyond the reach of the application (BTW, which OS you are using?).
In the long-running applications with sporadic logs an open-write-close sequence is usually recommended. There's also a really dirty fflush(fp); close(dup(fileno(fp))) trick.

PS: you may try to register fclose in an event handler for SIGINT.

Edited by nezachem: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.