How can I print a string with newline without flushing the buffer?

user2865166

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).

kaylum

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I print a newline without flushing the buffer?

How can I view the stdout buffer before flushing it?

How can I print a newline as \n in bash?

subprocess stdin buffer not flushing on newline with bufsize=1

How to print an string without the newline Mips Assembly language

How can I have a newline in a string in sh?

How can I split a string by newline in Shopify?

How do I print output without a trailing newline in Rust?

How to print without newline in CMake?

How to print without newline or space?

How to print without a newline or space

How to print without a newline in Golang?

How can I print [] without string in Python in YAML file

How can I print a string with the same length with or without multicharacters?

How can I print an string without the longest word

(How) can I split a long string in a maven property without having newline characters in the property value?

How can I suppress the newline after a print statement?

How can I suppress the newline after a print statement?

How can I print all outputs of this in newline instead in one line

How to print without a newline without using end=" "?

How can I read in characters with getchar() without the newline?

How to print "-n" without issuing a newline?

How can i print a list without the brackets?

How can i print page without header?

How can I split a string into an array on every newline?

How can I remove a newline from inside a string in C++?

How to print out a newline character in a string in Awk

How to not print <br/> in a string but get a newline instead

How do I print a variable in a shell script without altering trailing newline (if there is one)?