简体   繁体   中英

C programming: write to file without 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.

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;
}

I don't know if you can't disable the buffer, but you can force it to write in disk using fflush

More about it: (C++ reference, but just the same as in C): http://www.cplusplus.com/reference/clibrary/cstdio/fflush/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM