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.

Recommended Answers

All 2 Replies

Try googling setvbuf(). This function allows for unbuffered writes..

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.