How to animate the command line?

前端 未结 8 1904
臣服心动
臣服心动 2020-11-27 09:09

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar

8条回答
  •  遥遥无期
    2020-11-27 09:49

    below is my answer,use the windows APIConsoles(Windows), coding of C.

    /*
    * file: ProgressBarConsole.cpp
    * description: a console progress bar Demo
    * author: lijian 
    * version: 1.0
    * date: 2012-12-06
    */
    #include 
    #include 
    
    HANDLE hOut;
    CONSOLE_SCREEN_BUFFER_INFO bInfo;
    char charProgress[80] = 
        {"================================================================"};
    char spaceProgress = ' ';
    
    /*
    * show a progress in the [row] line
    * row start from 0 to the end
    */
    int ProgressBar(char *task, int row, int progress)
    {
        char str[100];
        int len, barLen,progressLen;
        COORD crStart, crCurr;
        GetConsoleScreenBufferInfo(hOut, &bInfo);
        crCurr = bInfo.dwCursorPosition; //the old position
        len = bInfo.dwMaximumWindowSize.X;
        barLen = len - 17;//minus the extra char
        progressLen = (int)((progress/100.0)*barLen);
        crStart.X = 0;
        crStart.Y = row;
    
        sprintf(str,"%-10s[%-.*s>%*c]%3d%%", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);
    #if 0 //use stdand libary
        SetConsoleCursorPosition(hOut, crStart);
        printf("%s\n", str);
    #else
        WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);
    #endif
        SetConsoleCursorPosition(hOut, crCurr);
        return 0;
    }
    int main(int argc, char* argv[])
    {
        int i;
        hOut = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleScreenBufferInfo(hOut, &bInfo);
    
        for (i=0;i<100;i++)
        {
            ProgressBar("test", 0, i);
            Sleep(50);
        }
    
        return 0;
    }
    

提交回复
热议问题