6

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.

Joy
  • 9,430
  • 11
  • 44
  • 95

2 Answers2

19

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;
}
AusCBloke
  • 18,014
  • 6
  • 40
  • 44
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/

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
  • You are referencing to a C++ header, although the question is tagged with C. – Roman Byshko Dec 05 '11 at 03:32
  • @Beginner: it's exactly the same stuff .. but I guess you're right, I'll add a warning – juliomalegria Dec 05 '11 at 03:36
  • It's not... believe me :) Make better reference to POSIX standard. But actually it would be even better to delete your answer, as I did it with mine... @AusCBloke has give a *full* answer. – Roman Byshko Dec 05 '11 at 03:38
  • @Beginner it is the same, at least in this case, and especially since: `C++ : Reference : C Library : cstdio (stdio.h) : fflush` – AusCBloke Dec 05 '11 at 03:40
  • @AusCBloke I just find this misleading (because of C++ there). This reference would be much better I think http://pubs.opengroup.org/onlinepubs/007904875/functions/fflush.html The link contains `cstdio` which is different from `string.h`. – Roman Byshko Dec 05 '11 at 03:43
  • @Beginner: I agree that is a better reference, another is http://man7.org/linux/man-pages/man3/fflush.3.html, but the ones at cplusplus.com aren't bad either since they include small examples, and the example there for `fflush` is completely C. – AusCBloke Dec 05 '11 at 03:44
  • @Beginner I'm pretty sure is the same because it is inside the C Library (http://www.cplusplus.com/reference/clibrary/). I don't like deleting my answers, at least not if they are correct. – juliomalegria Dec 05 '11 at 03:47
  • @julio.alegria: I don't see anything wrong with your answer, I use cplusplus.com a lot for C stuff. – AusCBloke Dec 05 '11 at 03:48
  • You can track this question, that I asked just now: http://stackoverflow.com/questions/8380805/difference-between-string-h-and-cstring – Roman Byshko Dec 05 '11 at 03:53