Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Console simple progress

4.67/5 (5 votes)
1 Feb 2013CPOL1 min read 35.2K  
A very simple console progress bar.

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).

Image 1

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!

C++
#include <windows.h>
#include <stdio.h>

void DoProgress( char label[], int step, int total )
{
    //progress width
    const int pwidth = 72;

    //minus label len
    int width = pwidth - strlen( label );
    int pos = ( step * width ) / total ;

    
    int percent = ( step * 100 ) / total;

    //set green text color, only on Windows
    SetConsoleTextAttribute(  GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN );
    printf( "%s[", label );

    //fill progress bar with =
    for ( int i = 0; i < pos; i++ )  printf( "%c", '=' );

    //fill progress bar with spaces
    printf( "% *c", width - pos + 1, ']' );
    printf( " %3d%%\r", percent );

    //reset text color, only on Windows
    SetConsoleTextAttribute(  GetStdHandle( STD_OUTPUT_HANDLE ), 0x08 );
}

void DoSome()
{
    int total = 1000;
    int step = 0;

    while ( step < total )
    {
        //do some action
        ::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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)