开发者

Rewrite in place - stdout

开发者 https://www.devze.com 2023-01-19 08:27 出处:网络
Because I\'m currently setting up a new server for use, I\'ve been using a lot of command-line programs like curl and wget, and I\'ve noticed that they do something interesting. When run in the Termin

Because I'm currently setting up a new server for use, I've been using a lot of command-line programs like curl and wget, and I've noticed that they do something interesting. When run in the Terminal, they print their current progress in place (e.g. 54% will become 55% in place, instead of 55% being printed on the next line - download a large file and you will see what I mean).

I've been wondering how programs can do this. Writing to stdout is nothing new to me, 开发者_运维技巧but I'm puzzled at how something like this would work. I've tried writing to stdout, then seeking backwards and writing again; printing backspace characters ('\b'), and printing new things; etc, but nothing seems to work.

Is there no API in Objective-C or C to do this? (C, for instance, has ungetc(), but no unputc()). Are there hacks that can achieve this?

Just something interesting I would like to know more about...

Thanks!


The most common method is using \r to return to the beginning of the line and rewriting the whole line, but \b should also work. Make sure you're calling fflush(stdout). And don't let the cursor move to a different line, or redrawing will be a lot more of a pain.


The ncurses project might also be of interest to you. Once you get beyond the simple stuff, you want to be focussing on the core of your app's logic, not its presentation!

GNU ncurses is used by just about every pretty terminal UI application you come across.


basically you can do it by something like this:

printf( "progress %3d%%\r", perc );

the \r returns to the start of the same line


Or S-Lang, which is viewed by many as the successor to ncurses.

0

精彩评论

暂无评论...
验证码 换一张
取 消