0

我正在尝试制作一个 C 程序来选择选项。如果我以这种方式运行它,它会起作用:

./select choice{1..5}
☐ choice1  ☐ choice3  ☐ choice5
☐ choice2  ☐ choice4

# outputs "choice1 choice2" on stdout

但如果我在反引号之间运行它,那就是地狱

`./select choice{1..5}` > choices.txt
☐ choice1☐ choice2☐ choice3☐ choice4☐ choice5

# Write "choice1 choice2" in `choices.txt`

我需要能够检索选定的选项。这就是为什么我将所有输出都输出到我打开的文件中

int tty = open("/dev/tty", O_RDWR);
/* Do my program using outputs on fd `tty` */
printf("%s\n", get_results());

我认为这与tgoto我的代码中的使用有关,用于在屏幕上移动书写光标。

if ((cm = tgetstr("cm", NULL)) == NULL)
    return (-1);
tputs(tgoto(cm, x, y), fd, &my_putchar);
return (0);

我已经看到 usingisatty(1)在反引号之间执行时返回 0,如果直接执行则返回 1... 那么,有没有办法让我在两种情况下移动光标并保持格式?

感谢您的时间

4

1 回答 1

0

问题中显示的代码片段使用termcap接口(不是curses)。它用

tputs(tgoto(cm, x, y), fd, &my_putchar);

wheremy_putchar可能会写入标准输出,就像程序的其余部分一样(使用printf)。如果程序被修改为将其所有屏幕输出写入标准错误,那么最后它可以将其结果写入标准输出,从而简化脚本。

无需打开/dev/tty;而是替换

printf("choice%d", n);

经过

fprintf(stderr, "choice%d", n);

当然my_putchar也换成类似的东西

int my_putchar(int c) { return fputc(c, stderr); }

是要走的路。

如果这是一个curses应用程序,可以使用newterm而不是更改输出流initscr对话框newterm当然使用。

于 2017-06-24T14:45:12.343 回答