Chinaunix首页 | 论坛 | 博客
  • 博客访问: 520434
  • 博文数量: 118
  • 博客积分: 3995
  • 博客等级: 中校
  • 技术积分: 1276
  • 用 户 组: 普通用户
  • 注册时间: 2005-11-15 12:15
文章分类

全部博文(118)

文章存档

2014年(1)

2013年(1)

2010年(6)

2009年(27)

2008年(10)

2007年(33)

2006年(38)

2005年(2)

我的朋友

分类: C/C++

2009-10-29 23:56:07

扫了一下wget的进度打印,里面有点复杂,主要是需要计算下载速度,考虑的问题也比较多;我弄了个简单的,貌似还能用。


#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>

const char * pre = "update"; // 显示在前面的提示
#define NPRE 10
#define NSUF 8
#define NSTAR 4
const char star[NSTAR] = {'|','/','-','\\'}; // 旋转符号

int main()
{
    int output_width = 80; // 瞎填的
    struct winsize winsz;
    char *str;
    char *sq;
    char perc[10];
    int n;
    int size;
    int nq,k;

    n = 0;
    while (n<100)

         /*获得窗口大小*/
        if (isatty(1) && ioctl(1, TIOCGWINSZ, &winsz) >= 0) {
            if (winsz.ws_col > output_width) output_width = winsz.ws_col;

             /*申请一个buffer*/
            if ((str = malloc(output_width))) {

                 /*首先都填满空格符*/
                memset(str, 0x20, output_width); // 0x20 is space
                memcpy(str, pre, strlen(pre));
                n++; // 进度

                /*写入转动的横线,和百分制的进度*/
                size = snprintf(perc, 10, " %c%3d%%", star[n%NSTAR], n);
                if (size > 0) {
                    snprintf(&str[output_width-size-NSUF], size, "%s",perc);

                    /*下面填入滚动箭头*/
                    sq = &str[NPRE];
                    nq = output_width - NPRE - size - NSUF -3;
                    k = n%nq+1;
                    memset(sq, '=', k);
                    sq[0] = '[';
                    sq[k] = '>';
                    sq[nq-1] = ']';

                    /*输出回车符,光标回到行首*/
                    write(1, "\r", 1);

                    /*输出进度,输出也可以使用printf函数,需要fflush*/
                    write(1, str, output_width);
                }

                /*睡1秒*/
                sleep(1);
            }
        }
}


阅读(854) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~