carl.hiass
carl.hiass

Reputation: 1774

Example of printf not flushing until newline

It seems that printf is only supposed to flush after a newline (or some other criteria). What would be a way to view this in code? For example, I tried the following test, but it seems to flush after each statement (the getchar I am guessing causes it to flush):

int main(void)
{

    printf("Hi");
    getchar();
    printf("OK!\n");

    return 0;
}

Output:

111 PrintF |
           ^
          cursor is here on first `printf`

Upvotes: 1

Views: 271

Answers (2)

carl.hiass
carl.hiass

Reputation: 1774

Here's a way to test with three different cases (on unix-like devices):

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

int main(void)
{

    printf("1. Before (unbuffered)");
    sleep(2);
    printf("After...\n");
    printf("------------------------------\n");

    // case 2 - newline
    printf("2. Before (newline)\n");
    sleep(2);
    printf("After...\n");
    printf("-----------------------------\n");

    // case 3 - autoflush
    printf("3. Before (manual flush)");
    fflush(stdout);
    sleep(2);
    printf("After...\n");
    printf("------------------------------\n");

}

Upvotes: 2

0___________
0___________

Reputation: 67820

void delay(unsigned someinteger) 
{ 
    clock_t start_time = clock(); 
  
    while (clock() < start_time + someinteger); 
} 

int main(void) 
{ 
        printf("start\n");
        printf("Hello");  delay(20000);
        printf("\n");
} 

See the delay between start and Hello. (some patience at the beginning required as I had to click run button)

enter image description here

Upvotes: 1

Related Questions