4

When I do this (note the included \n):

printf("Something.\n");

I would like it not to flush the buffer. I would like to manually flush it later.
Is this possible?

This question sort of asks the same thing, but asks about C++ instead of C. I don't see how I could gather how to do this in C by reading the answers to that question (so it's not a duplicate).

Community
  • 1
  • 1
  • [Here](https://www.gnu.org/software/libc/manual/html_node/Controlling-Buffering.html) are your options. – Eugene Sh. Oct 24 '16 at 21:25
  • @EugeneSh. So what you're saying is `stdout` is in `_IOLBF` mode (line buffering) and I should use `setvbuf` to switch it to `_IOFBF` mode (full buffering)? –  Oct 24 '16 at 21:30
  • Try it and tell us.. – Eugene Sh. Oct 24 '16 at 21:35
  • @EugeneSh. I can see how it would be used but I'm not sure exactly how to use it (specifically, I don't know what to pass for the `char *buf` parameter). Could you answer the question? –  Oct 24 '16 at 21:42
  • If you read the documentation, it explains that. Just pass NULL for the `buf` parameter and `setvbuf` will take care of it for you. – Carey Gregory Oct 24 '16 at 21:44
  • @EugeneSh. But I'm using `stdout` right? Why would I want to allocate any new memory? There is probably something about this stuff that I don't understand. –  Oct 24 '16 at 21:47
  • @QuintinSteiner: You are expected to do some research on your own. Namely reading the documentation and search for further information. If you have rpoblems with the C language, read a C book. We are no tutoring site, forum, etc. but a Q&A site. You ask a **specific** question, showing reasonable effort and providing all required information, you might get an answer. That's it. – too honest for this site Oct 24 '16 at 22:00

1 Answers1

2

As explained in the comments, setvbuf can be used to change the buffering of any file stream, including stdout.

Here is a simple example:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    setvbuf(stdout, NULL, _IOFBF, 0);
    printf("hello world\n");
    sleep(5);
}

The example uses setvbuf to make stdout fully buffered. Which means it will not immediately output upon encountering a newline. The example will only display the output after the sleep (flush on exit). Without the setvbuf the output will be displayed before the sleep.

kaylum
  • 13,833
  • 2
  • 22
  • 31