Linux to implement a simple color progress bar program __linux

Source: Internet
Author: User
Tags linux sleep sleep function usleep

When we install software under Linux, we often see a progress bar, as follows:
[########################################################] [100%] [/]

So, is there any way we can achieve a simple progress bar? Linux under the progress bar color is too monotonous, we have a way to achieve a color of the progress bar. It's fun to think about, let's take a look at the following.

In fact, a few lines of code can simulate a simple color progress bar, like this:

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

int main () {
    int i = 0;
    int j = 0;
    Char bar[102];
    Create a color array to store the colors
    int color[] = {1,2,3,4,5,6,7};
    Const char* Status = "|/-\\";
    memset (bar, 0, sizeof (bar));
    while (i <=) {
        printf ("\033[3%dm[%-100s]\033[0m\033[33m[%d%%]\033[0m[%c]\r", Color[j], bar, I, status[i% 4] );
        Refreshes the contents of the buffer
        fflush (stdout);
        bar[i++] = ' # ';
        Transform Color
        if (i% = = 0) {
            ++j
        ] per to 15% Delay 50 millisecond
        usleep (50000);
    }
    printf ("\ n");
    return 0;
}

Look at the results together:

is not cool, but after reading the code must still have a lot of friends still have some doubts, below I will explain the above code principle:

First, let's introduce the buffer
Buffer three kinds: No buffer, line buffer, full buffer.
No buffer: No buffer, that is, the information in the input and output, immediately input or output. The typical representative is the standard error stream stderr.
Row buffering: When input and output, I/O operations are encountered when I am experiencing a newline. A typical representation is the operation of the keyboard.
Full buffering: I/O operations are performed when the input and output fills the buffer. A typical representation is the reading and writing of a disk.

This implementation of the progress bar is a printf function , printf output function is a row buffer function, first write to the buffer, to meet the conditions of the buffer brush to the corresponding file. The buffer will be refreshed if one of the following conditions is true:
(1) Buffer filling
(2) The written character contains ' \ n ' \ r '
(3) Call Fflush flush buffer
(4) When the call scanf gets data from the buffer, the new buffer is also refreshed.

Because the output function is a row buffer type. So we need to use the buffer refresh function fflush to output. Otherwise, the progress bar we see will be a section of output.

There are two other symbols that need to be distinguished:' \ n ' \ r '. They have different meanings. ' \ n ' means a newline, pointing the cursor at the beginning of the next line. \ r is the beginning of each return. If we use the \ n progress bar The effect will be the following:

[#                                                           ] [1%] [\]
[##                                                          ] [2%] [-]
[###                                                         ] [3%] [/]
[####                                                        ] [4%] [|]
    **usleep function * 
    Once the buffer is refreshed, the result is output at once if the sleep function is not added. We can't see the loading process of the progress bar.
    Here's a unified summary of the Linux sleep functions: 
    header files: #include <unistd.h> 
    in seconds: unsigned int seconds (unsigned int); 
    In microseconds: int usleep (useconds_t usec); 
    In One-fourth milliseconds: extern void delay (unsigned int msec)

Finally, introduce the output color settings:
The printf function can implement the color and state of the output character by outputting a specific escape sequence.
The escape sequence begins with the control character ' ESC '. The ASCII code decimal representation of the character is 27, hexadecimal is 0x1b, and octal is 033. Most escape sequences are more than two characters, and are usually preceded by ' ESC ' and opening parenthesis ' ['. The starting sequence is called the Control sequence Guide (Csi,control Sequence Intro), usually replaced by ' \033[' or ' \e['.

The general format is as follows: (the display is the style, the foreground color is 30+, the background color is 40+, and the character m indicates the end)
\033[display mode; foreground color; background color m + output string
Or
\e[display mode; foreground color; background color m + output string

Common parameters are as follows:
Display mode: 0 (default), 1 (bold/highlight), 22 (not bold), 4 (single underline), 24 (No underline), 5 (flashing), 25 (no flicker), 7 (invert, flip foreground and background color), 27 (no inversion)
Color: 0 (Black), 1 (red), 2 (green), 3 (yellow), 4 (blue), 5 (magenta), 6 (green), 7 (white)

More detailed output color settings knowledge reference this big guy's blog: printf Output color settings

Friends, after you know this knowledge, go ahead and practice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.