How to Build a Real-Time Console Progress Bar in C
This article explains how to implement a console progress bar and countdown timer in C by covering carriage returns, newline handling, output buffering strategies, and the use of fflush to force immediate screen updates, complete with sample code and visual demonstrations.
In routine server operations we often see progress bars; this guide shows how to create such a progress bar using C.
1. Carriage Return and Newline
\n moves to the next line, while \r returns to the start of the current line; in C, \n typically performs both actions.
2. Output Buffering
Two example programs illustrate buffering effects. The first prints a message, sleeps for three seconds, and the output appears immediately because the string ends with \n (line buffering). The second omits \n, so the message stays in the buffer until the program ends.
The three buffering modes are:
Unbuffered – data is written directly to the device.
Line buffered – data is flushed when a newline is encountered.
Fully buffered – data is flushed only when the buffer is full.
These examples demonstrate that the console uses line buffering.
3. Countdown Program
Printing a decreasing number with printf("%d\r", count--); and sleep(1); creates a countdown, but without a newline the output remains buffered. Adding fflush(stdout); forces the buffer to flush, making the countdown visible.
For multi‑digit counts, use a width specifier such as printf("%2d\r", count--); to keep the cursor position consistent.
4. Progress Bar Program
The following code builds a 0‑100% progress bar that updates in place:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void ProcBar() {
int i = 0;
char proc[102];
memset(proc, '\0', sizeof(proc));
while (i <= 100) {
// left‑align within 100 characters
printf("[%-100s] [%d%%]\r", proc, i);
fflush(stdout);
proc[i] = '#';
usleep(100000); // 0.1 second
i++;
}
printf("
");
}
int main() {
ProcBar();
return 0;
}The program repeatedly prints a bar of # characters, updates the percentage, and flushes the output to create a smooth visual progress indicator.
Images below illustrate the behavior of the examples:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
