7

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.

4
  • 4
    Yes, set the second parameter of setbuf to NULL like this setbuf(myfilepointer, NULL);. Commented Dec 5, 2011 at 3:32
  • 5
    You guys know there's an awesome field down below labeled "Your Answer" where you can post this stuff Commented Dec 5, 2011 at 3:35
  • 1
    They've probably been burned by down voters! Commented Dec 5, 2011 at 3:36
  • 1
    I'd need to find a whole 10 more characters to post it as an actual answer! Commented Dec 5, 2011 at 4:10

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

+2, but it was impossible, so +1 only.
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/

9 Comments

You are referencing to a C++ header, although the question is tagged with C.
@Beginner: it's exactly the same stuff .. but I guess you're right, I'll add a warning
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.
@Beginner it is the same, at least in this case, and especially since: C++ : Reference : C Library : cstdio (stdio.h) : fflush
@AusCBloke I just find this misleading (because of C++ there). This reference would be much better I think pubs.opengroup.org/onlinepubs/007904875/functions/fflush.html The link contains cstdio which is different from string.h.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.