Create Your First Progress Bar Application with Linux

Linux | Red Hat Certified | IT Technology | Operations Engineer

👇 Join the technical exchange QQ group with 1000 members, note 【public account】 for faster approval

Create Your First Progress Bar Application with Linux

1. Concept of Newline

In the Linux system, \n and \r are two important escape characters, representing newline and carriage return respectively, each having different functions and application scenarios.


(newline character)

[Definition]: \n represents the newline character, its full English name is newline, and the control character can be written as LF (Line Feed). It moves the cursor to the beginning of the next line, commonly used to separate different lines of text.

[Function]: In the Linux system, \n is usually used to indicate a line break in text. When new characters are input, they will be output on a new line. This makes the text content clearer and more readable.

(carriage return character)

[Definition]: \r represents the carriage return character, its full English name is return, and the control character can be written as CR (Carriage Return). It moves the cursor to the beginning of the current line but does not move to the next line.

[Function]: In the Linux system, \r is usually used to continuously output different contents on the same line. If new characters are input, they will overwrite existing characters. This makes it possible to update text content within the same line.

When creating dynamic text outputs like progress bars, \r is very useful. By continuously updating the content of the same line, dynamic visual effects can be created.

The main function of \n is to create a line break, moving the cursor to the beginning of the next line; while the main function of \r is to return, moving the cursor to the beginning of the current line.

2. Line Buffering

In Linux, line buffering is a buffering mechanism used to store output data until a certain condition is met before sending the data out. Line buffering stores data by line, meaning that data is only sent when a newline character is included in the output data.

This buffering mechanism is very useful for scenarios that require bulk output, enhancing efficiency. Additionally, specific functions can be used to flush the buffer, forcing the buffered data to be sent out.

It is important to note that line buffering is just a buffering mechanism, and by default, not all outputs are line buffered; this can be changed through configuration files or specific functions in the code.

Thus, when dynamically displaying a text progress bar, we rely on \r for rollback rather than newline, which cannot meet the output data condition; at this point, we need to use fflush(stdout) to force the buffer to flush.

fflush(stdout) is a function used to flush the standard output stream(stdout). The standard output stream is a buffered stream; when data is written to the standard output stream, it is not displayed immediately but is first stored in the buffer. The buffer’s content is only displayed when it is full or when the fflush function is manually called.

3. Progress Bar Code

#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main() {
    // Progress bar code
    // 1. Array to store characters
    char bar[101]; // last store /0
    memset(bar, '#', 100);
    // rotating character array
    char label[4] = "-\|/"; // backslash needs to be escaped twice
    // 2. Loop to print
    int i = 0;
    while (i < 100) {
        bar[i + 1] = '\0';
        printf("[%-100s][%d%%][%c]\r", bar, i + 1, label[i % 4]); // add rotating identifier
        fflush(stdout); // flush buffer
        usleep(10000);
        bar[++i] = '#';
    }
    // 3. Final newline
    printf("\n");
    return 0;
}

We can open the vim editor on Linux to create the progress.c code, write the above progress bar code, and then use the make/makefile tool along with gcc to compile progress.c into an executable file named progress. Then, we can run the program by entering ./progress in the command line. The result is as follows:

Create Your First Progress Bar Application with Linux

Thus, we can simulate our first small program on Linux—the text progress bar!

When cleaning files, we can use make clean to delete files:

Create Your First Progress Bar Application with Linux

If we need to recompile the progress.c file, we can also use the make command:

Create Your First Progress Bar Application with Linux

The content of the Makefile is as follows:

Create Your First Progress Bar Application with Linux

Colorful Progress Bar

In C language, directly performing colorful output is not part of the standard since C language itself does not support this feature. However, if you write programs in a console environment and the target environment is Linux or some systems that support ANSI escape codes, you can use ANSI escape codes (ANSI escape sequences) to simulate color output.

For example, if you want to print a red message “Hello, World!” in the console, you can write:

#include <stdio.h>
int main() {
    if (isatty(fileno(stdout))) { // check if it is a terminal
        printf("\033[31m"); // set red font
        printf("Hello, World!\033[0m"); // print message and restore default color
    } else {
        printf("Hello, World!"); // for non-terminal devices, like files, print plain text
    }
    return 0;
}

In this example, if the program is run in a terminal, it will display the red “Hello, World!”; if not in a terminal (like redirecting output to a file), it will only display plain white text.

For colors, the following codes are commonly used:

Foreground Colors:

Black: \033[30m Red: \033[31m Green: \033[32m Yellow: \033[33m Blue: \033[34m Cyan: \033[36m Purple: \033[35m White: \033[37m

Background Colors:

Black: \033[40m Red: \033[41m Green: \033[42m Yellow: \033[43m Blue: \033[44m Cyan: \033[46m Purple: \033[45m White: \033[47m

Ending Color Settings: \033[0m or \x1b[0m (equivalent)

When you want to end the color output, you can use \033[0m to clear all settings. However, please note that this depends on whether the terminal supports these escape codes and the user’s terminal configuration. In the Windows console, since it does not support ANSI escape codes by default, the above method may not work.

So, for the progress bar code, we can set it to our preferred color by setting and canceling the font color before and after the loop printing, as shown in the code below:

Create Your First Progress Bar Application with Linux

Then we use the make command to recompile the progress.c source file:

Create Your First Progress Bar Application with Linux

The running result is as follows:

Create Your First Progress Bar Application with Linux

Simulating Real Download Speed Progress Bar

We need to use random numbers to simulate the progress of a download, then accumulate it into the progress bar instead of maintaining a constant speed of download. The code is as follows:

Create Your First Progress Bar Application with Linux

Then we can update the progress bar based on the proportion of each download amount, as shown in the code below:

Create Your First Progress Bar Application with Linux

The printing effect of the progress bar is as follows:

Create Your First Progress Bar Application with Linux

Create Your First Progress Bar Application with Linux

For course inquiries, add: HCIE666CCIE

↑ or scan the QR code above ↑

If you have any technical points or content you want to see

You can leave a message below to let us know!

Leave a Comment