中间命令行界面

Dan*_*ter 6 c io ncurses

我已经和C一起工作了一段时间,并且对简单的命令行界面非常熟练.我也玩过这个curses库,对于终端应用来说,不仅仅是写文本stdout.但是,我无法弄清楚中途点的位置 - 应用程序喜欢wgetmake拥有,例如,更新他们输出的文本的能力(如wget弹跳下载计量器和进度条),而不占用整个屏幕.

这种界面是我应该使用curses的,还是介于两者之间?优选地是跨平台的.

Ada*_*eld 10

你可以通过打印退格字符'\b'和原始回车'\r'(没有换行符)来做一些简单的事情.退格键将光标向后移动一个字符,允许您覆盖输出,回车符将光标移回当前行的开头,允许您覆盖当前行.

这是一个进度条的简单示例:

int progress = 0;
while(progress < 100)
{
    // Note the carriage return at the start of the string and the lack of a
    // newline
    printf("\rProgress: %d%%", progress);
    fflush(stdout);

    // Do some work, and compute the new progress (0-100)
    progress = do_some_work();
}
printf("\nDone\n");
Run Code Online (Sandbox Code Playgroud)

请注意,只有在写入实际终端时才应该这样做(而不是重定向到文件或管道).你可以测试一下if(isatty(fileno(stdout)) { ... }.当然,如果您使用任何其他库(如curses或ncurses),情况也是如此.

  • @larsmans:是的,好点(除了你想测试`stdout`是否是终端,而不是`stdin`). (2认同)