Search code examples
cfunctionprogress-barstatusbar

Status function bar - C


I have this function:

void choiceTwo(void){

    system("clear");
    printf("================ RUN ALL FUNCTION ================\n\n");

    printf("\nTest case 'create/destroy'... ");
    fflush(stdout);
    test_create_destroy();
    printf("OK\n");

    printf("Test case 'add/remove edge'... ");
    fflush(stdout);
    test_add_remove_edge();
    printf("OK\n");

    printf("Test case 'print graph'... ");
    fflush(stdout);
    test_print_graph();
    printf("OK\n");

    printf("Test case 'null'... ");
    fflush(stdout);
    test_null();
    printf("OK\n");

    printf("\nPress enter to continue ");
    getchar();
    getchar();
    main();
}

How can I print the status of this function by using a progress bar (in percent) like this in the picture?

Status Bar

I tried to do this using python, but do not know how to fully control the function status


Solution

  • try this code

    #include <stdio.h>
    #include <unistd.h>
    
    void working ( int showat, int done, int total) {
        char dash[51]  = "--------------------------------------------------";
        char blank[51] = "                                                  ";
        int portion = 0;
        float percent = 0.0f;
    
        printf ( "\033[?25l");//hide cursor
        printf ( "\033[38;5;10m");//green text
        printf ( "\033[48;5;0m");//on black
        printf ( "\033[%d;H", showat);//move curson to line showat
        percent = ( (float)done * 100) / total;
        portion = percent / 2.0f;
        printf ( "Progress: [\033[38;5;0m\033[48;5;10m");//black text on green
        printf ( "%.*s\033[38;5;10m\033[48;5;0m%.*s]%6.1f%% Complete\r"//back to green text on black
        , portion, blank, 50 - portion, dash, percent);
    
        printf ( "\033[0m");//reset color
        printf ( "\033[?25h");//show cursor
    }
    
    void test_progress ( ) {
        int item = 0;
        int allitems = 200;
        //do things in functioin where you need to show progress
        for ( item = 0; item <= allitems; item++) {
            working ( 5, item, allitems);
            usleep ( 50000);
        }
    }
    
    void test_loop ( ) {
        int item = 0;
        int allitems = 500;
        //do things in functioin where you need to show progress
        for ( item = 0; item <= allitems; item++) {
            working ( 9, item, allitems);
            usleep ( 50000);
        }
    }
    
    void choiceTwo(void){
    
        printf ( "\033[2J");//clear screen
        printf ( "\033[0;H");//move curson to line 0
        printf("================ RUN PROGRESS TEST ================\n\n");
    
        printf("\nTest progress'... ");
        test_progress();
        printf("\nOK\n");
    
    
        printf("\nTest loop'... ");
        test_loop();
        printf("\nOK\n");
    
    }
    
    int main()
    {
        choiceTwo ( );
        return 0;
    }