Download progress bar at terminal

Keywords: PHP

programme

<?php
// Refer to https://mengkang.net/1412.html
$width = exec("tput cols");

$progress = "[]100%";
$del = strlen($progress);
$width = $width - $del;

$progress = "[%-{$width}s]%d%%\r";
for($i=1;$i<=$width;$i++){
    printf($progress,str_repeat("=",$i),($i/$width)*100);
    usleep(30000);
}

echo "\n";

interpretative statement

  • tput cols obtains the "width" of the terminal, which is actually the number of character columns;
  • %S we know it's a placeholder for a string;
  • %-The meaning of {n}s is to occupy n characters. If the space is not enough, the position of the last value is fixed when outputting the progress bar;
  • %%Output percentage sign;
  • The most important point is that if the format is used at the end, move the cursor to the beginning of the line, and then the last whole line will be overwritten in the next output, giving the effect of dynamic change of the progress bar.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <unistd.h>

int main()
{
    struct winsize size;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &size);
    int width = size.ws_col;

    const char *progress = "[]100%";
    width = width - strlen(progress);

    char width_str[10] = {0};
    sprintf(width_str,"%d",width);

    char progress_format[20] = {0};

    strcat(progress_format,"[%-");
    strcat(progress_format,width_str);
    strcat(progress_format,"s]%d%%\r");

    // printf("%s\n",progress_format);
    // [%-92s]%d%%\r

    char progress_bar[width+1];
    memset(progress_bar,0,width+1);

    for(int i=1;i<=width;i++){
        strcat(progress_bar,"=");
        printf(progress_format,progress_bar,(i*100/width));
        // Or use
        // fprintf(stdout,progress_format,progress_bar,(i*100/width));
        fflush(stdout); // It is too laggy to refresh the cache area, otherwise it will look very caged.
        usleep(10000);
    }

    printf("\n");
    return 0;
}

Posted by ZaZall on Fri, 06 Dec 2019 05:30:46 -0800