Thursday, March 11, 2010

Avinash Joshi

♫ अविनाश जोशी >> Indian Patriot

Creating a progress bar in C

Posted by Avinash Joshi On October - 13 - 2009

I have been thinking about this for a long time… I always ask and wonder for myself, “How do I get a fancy progress bar in the terminal (i.e., using C/C++ code)???” I got this thought when I was coding for my huffman lab program. I was thinking “If we input a large file > 200 kb, It would take a long time to encode. So instead of giving the user a thought that the program has “hung”, we can have a progress bar!! :)”

 

So, with this thought in mind, I searched in google, but could not find a satisfactory answer. So, I went back to C basics and checked the escape character \r and that got me some idea… :)

 

This progress bar could be very useful for some or the other reason :D

 

So here is a simple code,

 

01 #include <stdio.h>
02
03 int  main(void) {
04     int i,j,k;
05     printf(“\n”);
06     for(i=0;i<=100;i++) {
07         /* The starting bracket [ */
08         printf("[");
09         /* Print the = until the current percentage */
10         for (j=0;j<i;j++)
11             printf("=");
12         /* If % is 60 then print 40 spaces (for the last ]) */
13         for (k=j;k<100;k++)
14             printf(” “);
15         printf(“]”);
16         /* % completed */
17         printf(” %3d%% completed”, i);
18         /* To delete the previous line */
19         printf(“\r”);
20         /* Flush all char in buffer */
21         fflush(stdout);
22         /* Just so that we can see the progress bar :) */
23         usleep(59000);
24     }
25     printf(“\n”);
26 }

SocialTwist Tell-a-Friend

4 Responses to “Creating a progress bar in C”

  1. Gunjan says:

    Ru sure u dint copy SuKu’s code?
    :P :P
    I doubt it ;)

  2. CantGetANick says:

    mfc one winblow and ncurses on gnu/linux are good option for really formatted output.
    by the way how much time we are talking here in encoding?

  3. Anurag says:

    Nice idea Avinash….

Leave a Reply

Locations of visitors to this page My India, My Pride