I want to know why this code instead of writing a letter each second waits to read all the letters before printing them.

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

int main ()
    FILE *fp;
    int c;

    fp = fopen ("hello.txt", "r");
    if (fp == NULL)
        perror ("Cannot open file");
        return (-1);
    while (1)
        c = fgetc (fp);
        if (feof (fp))
        printf("%c", c);
    fclose (fp);
    return (0);

1 Answer 1


The function printf writes to the standard output stream (aka stdout). The stdout usually buffers the data and then flushes it at some point (usually when a newline character is written or when it's told to).

You're not printing a newline after each recently-read character so the stdout buffers the recently-read character and then sleep is called, so nothing is displayed and this process repeats.

After the loop, you're printing a newline character so the buffered data is flushed and, therefore, is displayed at once. That'd be also the case if you didn't print a newline character because, by the end of a program, the standard streams are automatically flushed.

Another way you can force the stdout to flush the buffered data at some point is by calling a function from the standard library, namely fflush passing in stdout as an argument in this case.

// some code
printf("%c", c);
// some code


man fflush

in the terminal for more information!

You must log in to answer this question.