我使用C已经有一段时间了,并且精通简单的命令行界面。我还尝试过使用curses库,它适用于不只是向stdout写入文本的终端应用程序。然而,我不知道中间点在哪里-例如,像wget或make这样的应用程序有能力更新它们输出的文本(比如wget的跳跃下载计量器和进度条),而不会占据整个屏幕。
这类接口是我应该使用curses来实现的吗,还是在两者之间有一个步骤?最好是跨平台的。
发布于 2011-10-26 06:23:26
只需打印退格字符'\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");请注意,只有在写到实际的终端(而不是被重定向到文件或管道)时才应该这样做。您可以使用if(isatty(fileno(stdout)) { ... }进行测试。当然,如果您正在使用任何其他库,例如curses或ncurses,情况也是如此。
发布于 2011-10-26 06:26:39
在stdio和curses之间的是标准的Unix/POSIX termios库。关闭字符回显并读取一行的简单示例程序(注意,没有任何错误检查):
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
void munch_line()
{
int c;
while ((c = getchar()) != EOF && c != '\n')
;
}
int main()
{
int fd;
struct termios tio;
printf("Enter something: ");
tcgetattr(fileno(stdin), &tio);
tio.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), TCSANOW, &tio);
munch_line();
putchar('\n');
}在退出程序之前,不要忘记打开回显功能;)
发布于 2011-10-26 06:57:57
如果您的终端支持VT100 escape sequences,您可以使用它们来移动光标:
printf("\x1b[%uD", n); /* move cursor n steps to the left */
printf("\x1b[%uC", n); /* move cursor n steps to the right */
printf("\x1b[K"); /* clear line from cursor to the right */
printf("\x1b[1K"); /* clear line from cursor to the left */
printf("\x1b[2K"); /* clear entire line */一个快速示例(curtest.c):
#include <stdio.h>
int main(void)
{
printf("ZZZZZZZZZZ");
printf("\x1b[%dD", 10U); /* move cursor 10 steps to the left */
printf("YYYYYYYYY");
printf("\x1b[%dD", 9U); /* move cursor 9 steps to the left */
printf("XXXXXXXX");
printf("\x1b[%dD", 2U); /* move cursor 2 steps to the left */
printf("\x1b[1K"); /* clear line from cursor to the left */
printf("\r\n");
return 0;
}如果您的终端支持这些转义代码,则应打印
mizo@host:~/test> gcc curtest.c
mizo@host:~/test> ./a.out
XYZ
mizo@host:~/test>Windows命令行没有内置的VT100支持。
https://stackoverflow.com/questions/7896508
复制相似问题