如何使用 C++ 写入已打开的终端
在 linux 上,有 7+ 个步骤:
1) 打开一个终端
I find ctrl-alt t most convenient
press and hold ctrl and alt, then press t
There is also a selection LXTerminal on a mouse menu
Note - There is a way for your program to open a 'default' terminal,
and c++ can use the technique, but it is not c++, and I always seem to
need to change the defaults for my use.
2) 使用终端,您可以通过以下方式手动查找终端名称:
type the command "tty" into the terminal
Typical response on my system:
hostname@username:~$ tty
/dev/pts/1
在我的 Linux 系统上,终端名称的格式始终为“/dev/pts/x”,其中 x 是一个数字。
3) 对于我的程序(使用第二个终端),我的代码接受(终端响应的)x 部分作为命令参数 1,并使用该参数创建终端的路径文件名 (PFN)。
std::string aTermPFN = "/dev/pts/"; // partial address
aTermPFN += argv[1]; // ouput tty identified by argv[1]
// creating /dev/pts/<argv[1]>
// thus creating PFN of "/dev/pts/1"
4) 我的代码通常会在创建过程中提供对号码的确认。 (推荐)
std::cout << "accessing '" << aTermPFN
<< "' with std::ofstream " << std::endl;
5) 然后创建(或尝试创建)ofstream 对象
std::ofstream* ansiTerm = new std::ofstream(aTermPFN);
6) 并对其执行一些检查...
if (!ansiTerm->is_open())
{
std::cerr << "Can not access '" << aTermPFN << "'" << std::endl;
assert(0); // abort
}
7) 用完term后,一定要清理
ansiTerm->close();
delete ansiTerm;
// 如果使用适当的智能指针,可以避免删除。
现在到第二个终端的所有输出都使用“ansiTerm”对象,我碰巧在该代码中使用了一个更通用的术语(不是指针,而是引用):“termRef”。
使用示例
// mostly, in the app where these sample exist, I output text at computed
// screen locations
// ansi terminals provide goto row col ansi functions
// the style is simply position the cursor,
termRef << m_ansi.gotoRC(3, col) << ss.str() << std::flush;
// then output text-----------------^^^^^^^^ (ss is stringstream)
// ansi terminals can clear
void clearScr() { termRef << m_ansi.clrscr() << std::flush; }
// ansi terminals can draw simple borders (not-fancy)
{ // across top gotoRC (int row, int col )
termRef << m_ansi.gotoRC ( tlcRow, tlcCol+1);
for ( int i=0; i<borderWidth; ++i) termRef << m_acs.HLINE;
termFlush();
}