首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中间命令行界面

中间命令行界面
EN

Stack Overflow用户
提问于 2011-10-26 06:09:49
回答 4查看 2.1K关注 0票数 5

我使用C已经有一段时间了,并且精通简单的命令行界面。我还尝试过使用curses库,它适用于不只是向stdout写入文本的终端应用程序。然而,我不知道中间点在哪里-例如,像wgetmake这样的应用程序有能力更新它们输出的文本(比如wget的跳跃下载计量器和进度条),而不会占据整个屏幕。

这类接口是我应该使用curses来实现的吗,还是在两者之间有一个步骤?最好是跨平台的。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-10-26 06:23:26

只需打印退格字符'\b'和原始回车'\r' (不带换行符),就可以做一些简单的事情。退格键将光标向后移动一个字符,允许您覆盖输出,回车符将光标移回当前行的开头,允许您覆盖当前行。

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

代码语言:javascript
复制
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,情况也是如此。

票数 11
EN

Stack Overflow用户

发布于 2011-10-26 06:26:39

stdiocurses之间的是标准的Unix/POSIX termios库。关闭字符回显并读取一行的简单示例程序(注意,没有任何错误检查):

代码语言:javascript
复制
#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');
}

在退出程序之前,不要忘记打开回显功能;)

票数 4
EN

Stack Overflow用户

发布于 2011-10-26 06:57:57

如果您的终端支持VT100 escape sequences,您可以使用它们来移动光标:

代码语言:javascript
复制
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):

代码语言:javascript
复制
#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;
}

如果您的终端支持这些转义代码,则应打印

代码语言:javascript
复制
mizo@host:~/test> gcc curtest.c 
mizo@host:~/test> ./a.out
       XYZ
mizo@host:~/test>

Windows命令行没有内置的VT100支持。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7896508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档