Topic: Question concerning printf()

hi there. i've got a little question concerning printf(). why is it that when i compile&run the following code:

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

int
main(void)
{

printf("HELLO WORLD!");
sleep(5);
}

"HELLO WORLD!" gets printed after the 5 second delay and not beforehand?

cheers.

p.s.: ...and YES! i do want printf without a new-line character at the end!

Re: Question concerning printf()

because stdio is line-buffered by default, so things you print only shows up on screen after you either print a newline character, fill up the buffer, or exit the process. You can flush the buffer with fflush(3). Your program with the fflush added would look like this:

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

int main() {
    printf("HELLO WORLD!");
    fflush(stdout);
    sleep(5);
    return 0;
}

Re: Question concerning printf()

line-buffered by default: Just curious to know if there's a way to change this default behavior ?

<wintellect> NetBSD users are smart enough to accept that there's no 3D support tongue

Re: Question concerning printf()

There is. You can disable the ICANON flag using tcsetattr. Here's an example program I wrote a couple of years ago to demonstrate just this to wintellect: http://www.maxlor.com/temp/nonblock.c (well, actually the goal of this program was to show non-blocking I/O, but disabling line buffering is part of it)

Re: Question concerning printf()

Thank you!

<wintellect> NetBSD users are smart enough to accept that there's no 3D support tongue

Re: Question concerning printf()

thanks a bunch for the hint. that completely solved all of my problems. smile

cheers.

Re: Question concerning printf()

Maxlor wrote:

There is. You can disable the ICANON flag using tcsetattr. Here's an example program I wrote a couple of years ago to demonstrate just this to wintellect: http://www.maxlor.com/temp/nonblock.c (well, actually the goal of this program was to show non-blocking I/O, but disabling line buffering is part of it)

Ah yes - I remember that.

"UBER" means I don't drink the coffee... I chew the beans instead
             -- Copyright BSDnexus