C语言 如何使用 printf 制作“进度条”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20947161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a "progress bar" using printf?
提问by qweruiop
Many command line tools implement text-based progress bar. Like rpm installing:
许多命令行工具实现了基于文本的进度条。像 rpm 安装:
installing ##############[45%]
安装##############[45%]
the #grows with the percentage, while keeps itself in a single line. What I want is something similar: I need a progress indicator taking just one line, that is to say, when percentage grows, it got overwritten, instead of make a new line(\n).
该#增长与比例,同时保持自身在一行。我想要的是类似的东西:我需要一个只占一行的进度指示器,也就是说,当百分比增长时,它会被覆盖,而不是创建一个新行(\n)。
I tried this:
我试过这个:
#include <stdio.h>
int main (){
int i = 0;
for (i = 0; i < 10000; i++){
printf("\rIn progress %d", i/100);
}
printf("\n");
}
\rworks to overwrite the single line. However, \rbrings cursor to the beginning of line and printfbrings cursor to the end, which result in a rapidly waving cursor. You guys can feel it by a little compiling. Can Anyone come up with alternatives to avoid this issue?
\r可以覆盖单行。但是,\r将光标移至行首并将printf光标移至行尾,这会导致光标快速摆动。大家稍微编译一下就可以感受到了。任何人都可以想出替代方法来避免这个问题吗?
采纳答案by Alan Haggai Alavi
This is a problem of the stdoutstream being buffered. You have to flush it explicitly (implicit flushing occurs with a \n) using fflush(stdout)after the printf():
这是stdout流被缓冲的问题。您必须在以下\n使用fflush(stdout)之后显式刷新它(使用 a进行隐式刷新)printf():
fflush(stdout);
回答by Lee Duhem
回答by haylem
Rather than giving your some erroneous and non-portable code lines, I'd recommend you to read through the man pages for your system's termcapand terminfo. It's a bit hard to follow at first, but it's a must-read if your about to start mucking with terminal-dependent code. The Wikipedia pages are a good place to start, but then do give the man pages on your system a read as well.
与其给你一些错误的和不可移植的代码行,我建议你通读系统的termcap和terminfo的手册页。一开始有点难以理解,但是如果您即将开始使用依赖于终端的代码,则必须阅读它。维基百科页面是一个很好的起点,但也请务必阅读系统上的手册页。
Also I just realized your question is most definitely a duplicateof a few other questions.
此外,我刚刚意识到您的问题绝对是其他一些问题的重复。
回答by ArmaAK
I believe using
我相信使用
printf("\e[?25l");
may be able to help. This will hide the cursor. Honestly, I'm not sure if using /r or printf again will override that bit of code and show the cursor, but it's worth a shot. Also, the below code can be used to show the cursor again.
也许可以提供帮助。这将隐藏光标。老实说,我不确定再次使用 /r 或 printf 是否会覆盖那段代码并显示光标,但值得一试。此外,以下代码可用于再次显示光标。
printf("\e[?25h");
回答by jmlemetayer
To use formatting on your terminal, check the ANSI escape code.
要在终端上使用格式,请检查ANSI 转义码。

