0

This is my sample program for simulating a Loading progress. The only problem I'm facing right now is clearing my previous output of "Loading: %i"

/* loading program */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define TIMELIMIT 5

int main()
{
    for(int i = 0, j; i < 5; ++i) {
        j = i;
        printf("Loading: %i%%", ++j);
        sleep(1);
    //system("bash -c clear");    not working
    //printf("\033[2J\033[1;1H"); clears whole screen with no output at all
    }
    return(0);
}

3 Answers3

1

if you print \r instead of \n using printf, then it will return to the beginning of the same line instead of the next line. Then you can re-print the new status on top of the old line.

Mobius
  • 2,871
  • 1
  • 19
  • 29
  • @Seek Addo tried it this way printf("Loading: %i%%\r", ++j); shows me the last output but blanks out the rest/no output at all Same with bunch of printf("\n"); and printf("\r"); –  Mar 01 '17 at 04:38
  • sorry for some reason i did not realize you were in `C`. But I see you found that you have to call `fflush(stdout)`, so all is well – Mobius Mar 01 '17 at 13:48
1

Anyway here is the correct code. Thanks to Mobius and Dmitri.

/* loading program */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define TIMELIMIT 5

int main()
{
    for(int i = 0, j; i < TIMELIMIT; ++i) {
        j = i;
        printf("Loading: %i%%", ++j);
        printf("\r");
        fflush(stdout);
        sleep(1);
    }
    return(0);
}
0

I think the answer to this question is system("reset"). This is the command you're looking for

    reset

this command clears your whole terminal.

and your code go like this,

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define TIMELIMIT 5

int main()
{
    int i,j;
    for(int i = 0, j; i < 5; ++i) {
        j = i;
        system("reset");
        printf("Loading: %i%%\n", ++j);
        sleep(1);
    //system("bash -c clear");    not working
    //printf("\033[2J\033[1;1H"); clears whole screen with no output at all
    }
    return(0);
}
amit kumar
  • 61
  • 1
  • 1
  • 2