用C写了个进度条函数,结果光标跳来跳去的

sh/bash/dash/ksh/zsh等Shell脚本
回复
rikhtdss
帖子: 115
注册时间: 2006-09-08 18:57
联系:

用C写了个进度条函数,结果光标跳来跳去的

#1

帖子 rikhtdss » 2014-10-14 14:33

代码: 全选

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

/* 打印进度条 */
void DisplayProgress(long current, long total) {
    int width = 50; /* 进度条宽度为 50 个字符 */
    int i;
    /* 清空行 */
    for (i = 0; i < width + 7; i++) {
        putchar('\b');
    }
    
    int LoopTimes = (int)((double)current / total * width);

    putchar('[');
    for (i = 0; i < LoopTimes; i++)
        putchar('#');
    for (i = 0; i < width - LoopTimes; i++)
        putchar('-');
    printf("] ");
    printf("%3.0f%%", (double)current / total * 100);    
}

int main(void)
{
    int start = 1, end = 285;
    int i;
    for (i = start; i <= end; i++) {
        DisplayProgress(i, end);
        usleep(100000);
    }
    printf(" Done!\n");
    return 0;
}

怎么在函数完成一轮输出后将光标移到行尾?
__slucx__
帖子: 2
注册时间: 2012-10-31 9:20
系统: Debian

Re: 用C写了个进度条函数,结果光标跳来跳去的

#2

帖子 __slucx__ » 2014-10-14 14:44

函数DisplayProgress结尾加fflush(stdout);
rikhtdss
帖子: 115
注册时间: 2006-09-08 18:57
联系:

Re: 用C写了个进度条函数,结果光标跳来跳去的

#3

帖子 rikhtdss » 2014-10-14 15:00

解决了,谢谢楼上!
往事remember
帖子: 1
注册时间: 2014-12-31 13:40
系统: xp

Re: 用C写了个进度条函数,结果光标跳来跳去的

#4

帖子 往事remember » 2014-12-31 16:42

我想问一下楼主,把你的程序跑起来之后,为什么后面会出现很多%号
回复