而用C显示执行完毕% [英] displaying % completed while executing in C

查看:100
本文介绍了而用C显示执行完毕%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在像5分钟来执行的C程序。所以我在想,如果我能像显示完成的百分比或在执行用户的任何类型的交互,因为闪烁的光标是有点沉闷。
我在想显示比例,但我可以像删除不知何故,例如,如果任务1结束,我把25%再经过2号任务结束的25%变成50%?

I have a C program that is taking like 5 minutes to execute. So I was thinking if I can like show the percentage completed or any type of interaction for the user while executing, since a blinking cursor is a bit dull. I was thinking of displaying percentage but can I like erase somehow, eg if task 1 ended I put 25% then after task 2 ends the 25% becomes 50%?

给我你输入一些良性互动
干杯!=)

Give me your input on some good interactions cheers!=)

推荐答案

这实质上是在推出一两个问题:

This is essentially two questions rolled in to one:


  • 如何的计算百分比的基于任务流程

  • 如何的 present 的计算

  • How to calculate percentage based on task flow
  • How to present the calculation

首先要看你的程序是如何构造的,而且可能是最容易被想到你的程序流程的上下文中的问题的回答。第二可以以无数的方式,其中最简单的是由其它说明来完成已,即:

The first depends on how your program is constructed, and is probably easiest answered by thinking about the problem within the context of your program flow. The second can be done in a myriad of ways, of which the simplest have been explained by others already, namely:


  • 使用 \\ r 跳转到行的开头

  • 使用 \\ b 的x次移动光标回到

  • Using \r to jump to the beginning of the line
  • Using \b x number of times to move the cursor back

我用它尚未提及的第三条道路,那就是的保存的和的恢复的光标位置。这使您可以随意移动光标周围。

I've used a third way which hasn't yet been mentioned, and that is to save and restore the cursor position. This allows you to arbitrarily move the cursor around.


  • \\ E [S 存储当前光标位置

  • \\ E [U 光标恢复到那个位置

  • \e[s stores the current cursor position
  • \e[u restores the cursor to that position

下面是一个例子:

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

int main(int argc, const char *argv[]) {

    int i;
    int tasks = 25;

    printf("Progress:\e[s");

    for(i = 0; i < tasks; i++) {
        int pct = ((float) i / tasks) * 100;

        printf(" %2d (%3d%%)\e[u", i, pct);
        fflush(stdout);

        sleep(1);
    }

    return(0);
}

请注意,我们不关心的行的开头是:我们只重印实际比例。你会注意到光标位置现在是个前可见的权利,但你可以任意移动任何你喜欢的。

Note that we don't care where the beginning of the line is: we only reprint the actual percentage. You'll notice that the cursor position is now visible right before the percentage, but you can arbitrarily move it anywhere you like.

该解决方案假定你的终端能够理解这些ANSI命令,其中的可以的从终端到不同的终端。虽然我觉得上述方法相对安全的,看看的terminfo /的 ncurses的了解这一点。

This solution assumes that your terminal is capable of understanding these ANSI commands, which can differ from terminal to terminal. Although I think the aforementioned approach is relatively "safe", have a look at terminfo / ncurses for more on that.

更新日志:


  • 重写了最后一段

  • 替换我的初步bash的例子有
    一个C的例子

这篇关于而用C显示执行完毕%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆