C programming: writing to a file without a buffer

I use fputs to write lines to a file, but in debug mode, the contents are not written to disk after fputs is approved. I think there is some buffer. But I would like to debug to verify the logic is correct by viewing the content directly. Is there any way to disable the buffer? Thank.

+5
source share
2 answers

You have several alternatives:

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

Where fis obviously yours FILE*.

t

#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;
}
+16
source

I don’t know if you can disable the buffer, but you can make it write to disk using fflush

: ( ++, , C): http://www.cplusplus.com/reference/clibrary/cstdio/fflush/

0

All Articles