Introduction
This article introduces a progress bar for any job that you may have in console.
Sometimes a task running within a program might take a while to
complete. A user-friendly program provides some indication to the user that the task is occurring, how long the task might take, and how much
work has already been done. One way of indicating work, and perhaps the amount of progress, is to use an animated text or image.
The idea is that you may want to print some data to the terminal to show the progress of your algorithm, but displaying it all could be too much. A typical example
will print a progress 'bar' so that you can see how long is taking your computing (as a pacifier).
Using the code
This code is developed on Windows but it can be easily be adapted and used in any console project in Unix or Linux.
This progress bar is used in some apps like wget, upx, dropbox uploader and many others. You can customize these functions for your needs, a thank you message will do the trick with me!
#include <windows.h>
#include <stdio.h>
void DoProgress( char label[], int step, int total )
{
const int pwidth = 72;
int width = pwidth - strlen( label );
int pos = ( step * width ) / total ;
int percent = ( step * 100 ) / total;
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN );
printf( "%s[", label );
for ( int i = 0; i < pos; i++ ) printf( "%c", '=' );
printf( "% *c", width - pos + 1, ']' );
printf( " %3d%%\r", percent );
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), 0x08 );
}
void DoSome()
{
int total = 1000;
int step = 0;
while ( step < total )
{
::Sleep( 50 );
step+=1;
DoProgress( "Download: ", step, total );
}
printf( "\n" );
}
int main()
{
DoSome();
return 0;
}
Points of Interest
It is nice to place progress bars in console apps, but sometimes there is no time to create them. So I wrote some functions to be used in all
console apps. Take a look at the screenshot to understand the whole behavior.