Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming: write to file without buffer

Tags:

c

buffer

I am using fputs to write strings to file, but under the debug mode, the content is not written to disk after the statement fputs. I think there is some buffer. But I would like to debug to check whether the logic is correct by viewing the content directly. Is there anyway to disable the buffer? Thanks.

like image 525
Joy Avatar asked Dec 05 '11 03:12

Joy


1 Answers

You have a couple of alternatives:

  • fflush(f); to flush the buffer at a certain point.
  • setbuf(f, NULL); to disable buffering.

Where f is obviously your FILE*.

ie.

#include <stdio.h>

int main(void)
{
   char s[100];

   FILE *f = fopen("test.txt", "w");
   setbuf(f, NULL);

   while (fgets(s, 100, stdin))
      fputs(s, f);

   return 0;
}

OR

#include <stdio.h>

int main(void)
{
   char s[100];

   FILE *f = fopen("test.txt", "w");

   while (fgets(s, 100, stdin)) {
      fputs(s, f);
      fflush(f);
   }

   return 0;
}
like image 69
AusCBloke Avatar answered Oct 01 '22 14:10

AusCBloke