How to Flush stdout Output Stream in C

Jinku Hu Feb 02, 2024
  1. Use the fflush Function to Flush stdout Output Stream in C
  2. Demonstrate fflush Behavior Using printf Function in C
How to Flush stdout Output Stream in C

This article will demonstrate multiple methods about how to flush the stdout output stream in C.

Use the fflush Function to Flush stdout Output Stream in C

C standard library provides an I/O library, stdio, that essentially represents a buffered version of I/O operations done in userspace, thus improving performance for common use-cases. Generally, accessing files and conducting operations on them is provided by the operating system services; thus, the user eventually needs a system call e.g. to open a file. A frequent invocation of system calls makes the program slower as it entails accessing operating system kernel data-structures and transferring control back and forth. As a result, there are buffers maintained by the C library for handling the input/output operations when using the stdio function calls.

If the user needs to force writing to kernel buffers, it needs to flush the given stream provided by the fflush function. fflush takes a single argument of FILE pointer to the given stream. Note that fflush forces write function for output streams while discarding any buffered data for input streams (with seekable files). If the argument is NULL, it flushes all open output streams.

Mind though, fflush does not ensure that written data is physically stored as that requires the kernel buffers to be flushed (which can be accomplished using fsync call seen here).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  char *username;
  size_t len;
  int lnmax = 256;

  username = malloc(lnmax);
  if (username == NULL) perror("malloc");

  printf("Username: ");
  fflush(stdout);
  if (fgets(username, lnmax, stdin) == NULL) exit(EXIT_FAILURE);

  printf("Your username is set to - %s", username);

  exit(EXIT_SUCCESS);
}

Output:

Username: tmp
Your username is set to - tmp

Demonstrate fflush Behavior Using printf Function in C

Note that some streams (e.g. stderr) are not buffered. In contrast, the printf function that implicitly writes to stdout stream is buffered, and if we execute the infinite loop printing a single character each iteration underneath the hood, it will not output the contents to the stream until the internal buffer is full. Thus, the following code example results in burst printing the bullet chars. Notice that we call the usleep function every iteration to slow down the human eye’s execution to be clearly observable.

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

int main(int argc, char *argv[]) {
  while (1) {
    printf(".");
    usleep(1e3);
  }

  exit(EXIT_SUCCESS);
}

Alternatively, if we substitute the printf call with fprintf, which prints to stderr stream, it will yield the iterative char by char printing behavior each second. Again, the 1-second delay every iteration is put to only ensure a good demonstration.

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

int main(int argc, char *argv[]) {
  while (1) {
    fprintf(stderr, ".");
    sleep(1);
  }

  exit(EXIT_SUCCESS);
}

Finally, if we needed to imitate the same behavior on the stdout stream as seen in the previous example code, we can add the fflush call after the printf function. This will force the C library buffers to be written to kernel buffers each iteration, resulting in similar behavior.

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

int main(int argc, char *argv[]) {
  while (1) {
    printf(".");
    fflush(stdout);
    sleep(1);
  }

  exit(EXIT_SUCCESS);
}
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C IO