我想使用 ncurses 编写一个简单的程序来显示一些数据。然后我希望程序以这样的方式写入标准输出,然后我可以在命令行上使用管道 (|) 将一些数据通过管道输出。
我目前的尝试不起作用。我可以使用“>”在文件中看到“GOT HERE”,但还有一大堆其他东西。程序也会立即退出。
#include <stdio.h>
#include <ncurses.h>
int main(int _argc, char ** _argv)
{
initscr(); /* Start curses mode */
printw("Hello World !!!"); /* Print Hello World */
refresh(); /* Print it on to the real screen */
getch(); /* Wait for user input */
printf("GOT HERE");
endwin(); /* End curses mode */
printf("GOT HERE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是使用 > 的最终输出
^[[?1049h^[[1;29r^[(B^[[m^[[4l^[[?7h^[[H^[[2JHello World !!!^MGOT HERE^[[29;1H^[[?1049l^M^[[?1l^[>GOT HERE
Run Code Online (Sandbox Code Playgroud)
是否可以stdout通过管道和 ncurses 同时使用?
这已经 5 岁了,你可能已经继续前进了,但这是我搜索结果的顶部,所以我想我会添加我找到的解决方案。在尝试让管道在上面的 bash 示例等代码中工作很多次之后,我终于找到了一个用 newterm 命令暗示正确方向的人。唯一的技巧是打开一个新的 tty 并使用 newterm 而不是 initscr:
#include <stdio.h>
#include <ncurses.h>
int main(int argc, char ** argv) {
FILE *f = fopen("/dev/tty", "r+");
SCREEN *screen = newterm(NULL, f, f);
set_term(screen);
//this goes to stdout
fprintf(stdout, "hello\n");
//this goes to the console
fprintf(stderr, "some error\n");
//this goes to display
mvprintw(0, 0, "hello ncurses");
refresh();
getch();
endwin();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有了这个,你可以在任何你想要的地方传输 stdout 和 stderr,但有一个 ncurses 会话。我不确定它有多便携,或者是否有任何其他问题,只是很高兴找到一个有效的解决方案。
默认情况下,curses 写入标准输出,这是您的管道所在的位置。但是curses 有两个不同的初始化函数:initscr和newterm。后者让你做被问到的事情,就像这样:
#include <stdio.h>
#include <ncurses.h>
int main(int _argc, char ** _argv)
{
newterm(NULL, stderr, stdin); /* Start curses mode */
printw("Hello World !!!"); /* Print Hello World */
refresh(); /* Print it on to the real screen */
getch(); /* Wait for user input */
printf("GOT HERE");
endwin(); /* End curses mode */
printf("GOT HERE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)