我希望能够通过命令替换调用基于ncurses的程序,因此它的输出可以作为命令行参数传递给另一个程序。例如,当程序没有进入curses模式时,这在bash中很容易做到:
echo $(pwd) # should be the same as just calling pwd alone
当我尝试使用我的程序(其代码如下)时,从不输入curses模式,并且永远不会打印字符串“test”。进入curses模式非常重要,因为从理论上讲,用户会以某种方式操纵最终打印到stdout的字符串(现在字符串只是静态的)。
echo $(./a.out) # just prints an empty line
我的程序将在输入curses模式后正常运行时返回字符串“this is not a test”,“test”将打印到屏幕上,并且用户按下一个键。
./a.out # normal run
以下是有问题的代码:
// test.cpp
#include <ncurses.h>
#include <iostream>
using namespace std;
/* get curses up and running */
void init() {
initscr(); // start curses mode, might clear screen
raw(); // disable line buff, and C-z/C-c won't gen sigals; see cbreak()
keypad(stdscr, TRUE); // enable arrow keys and function keys
noecho(); // don't echo chars user types
}
/* shut curses down */
void end() {
endwin(); // end curses mode
}
int main()
{
init();
printw("test");
getch();
end();
cout << "this is not a test" << endl;
return 0;
}
我用这个命令编译:
g++ test.cpp -lcurses
感谢您的帮助!
答案 0 :(得分:2)
这是一个简单的解决方案,使用newterm
:
#define _XOPEN_SOURCE
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
// start curses mode
SCREEN* s = NULL;
FILE* out = stdout;
if(!isatty(fileno(stdout))) {
out = fopen("/dev/tty", "w");
// Should really test `out` to make sure that worked.
setbuf(out, NULL);
}
// Here, we don't worry about the case where stdin has been
// redirected, but we could do something similar to out
// for input, opening "/dev/tty" in mode "r" for in if necessary.
s = newterm(NULL, out, stdin);
printw("test");
getch();
endwin(); // end curses mode
delscreen(s);
puts("/home/matt");
return 0;
}