user2355660
user2355660

Reputation:

update screen line in C console app (unix)

I want to update the screen in my C console app. I want to do a console progress bar. How can I? Look at this:

Downloading...
|==== | 34%
to:
Downloading...
|===== | 50%
these must be on the same line, I have to update that line.

Upvotes: 2

Views: 4278

Answers (4)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

You can simply use \b chars to clear your line. printf("\b\b\b\b\b\b%5d",value); fflush(stdout). This is a very simple way of doing it. Of course, if you need to do more complex things, editing multiple lines, coordinates management, you should consider using curses.

Upvotes: 0

Gilbert
Gilbert

Reputation: 3776

On many systems \r can be used to overwrite the line.. you just need to be sure to flush the line somehow.

static const char equals[] = "=====....=====";  // 50 toal ='s

float percent;   // percentage... assuming you need floating
int   p;         // integer percentags

for ( percent = 0.0; percent < 100.0; percent++ )
{
    p = percent + 0.5;
    fprintf( stdout, "\r|%.*s | %d", p/2,equals, p );
    fflush(stdout);   // assure line written, even without \n
}

p = percent + 0.5;
printf( "\r|%.*s | %d\n", p/2,equals, p );  // final line with \n

Now is the time for the reader to beware of uncompiled and untested code.

Upvotes: 0

Naffi
Naffi

Reputation: 730

#include <stdlib.h>
#include<stdio.h>
int main(void)
{
    int i = 0;
    for(i = 0; i <= 100; i+= 10)
    {
        int j;
        for(j = 0; j <= i/10; j++)
            printf("=");

        printf("%d\n",i);
        sleep(1);
        system("clear");
    }
}

Upvotes: -1

Leo Chapiro
Leo Chapiro

Reputation: 13984

Take a look at this example: http://www.rosshemsley.co.uk/2011/02/creating-a-progress-bar-in-c-or-any-other-console-app/

The point is:

We must first write the correct escape sequence so that the terminal will know to execute the next symbols as a command. In C this escape code is “\033[". We then follow this by any command we like. In this example we use "\033[F" to go up one line followed by "\033[J" to clear a line. This erases the line where the load bar used to be, and positions the cursor so that we can re-write that same line again.

// Process has done i out of n rounds,
// and we want a bar of width w and resolution r.
static inline void loadBar(int x, int n, int r, int w)
{
    // Only update r times.
    if ( x % (n/r) != 0 ) return;

    // Calculuate the ratio of complete-to-incomplete.
    float ratio = x/(float)n;
    int   c     = ratio * w;

    // Show the percentage complete.
    printf("%3d%% [", (int)(ratio*100) );

    // Show the load bar.
    for (int x=0; x<c; x++)
       printf("=");

    for (int x=c; x<w; x++)
       printf(" ");

    // ANSI Control codes to go back to the
    // previous line and clear it.
    printf("]\n\033[F\033[J");
}

Upvotes: 2

Related Questions