【问题标题】:How to get the terminal dimensions in C++ code? [duplicate]如何在 C++ 代码中获取终端尺寸? [复制]
【发布时间】:2014-05-31 17:30:56
【问题描述】:

我最近试图获取运行该程序的终端的大小。
问题是脚本+程序方案不方便,不支持用户输入或终端大小变化。

如何在 C++ 代码中做到这一点(不会弄乱脚本)?
我的代码:
Bash 文件(要运行的文件而不是 C++ 程序):

cols=`tput cols`
lines=`tput lines`
input="${cols}\n${lines}"
echo -ne "${input}" | [C++ program]

C++ 文件(实际程序):

#include <iostream>

int main() {
  unsigned lines;
  unsigned cols;
  cin >> cols;
  cin >> lines;
  // some code here
}

【问题讨论】:

  • 使用ncurses
  • system("tput cols")... 可以做到我认为的伎俩,但我从未尝试过。
  • 你也必须链接到ncurses。
  • 编译命令末尾通常是-lncursesw-lncurses

标签: c++ c linux bash terminal


【解决方案1】:

如图所示

Getting terminal width in C?

您可以通过 ioctl 调用获取终端大小

#include <sys/ioctl.h>
#include <stdio.h>

int main (void)
{
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);

    printf ("lines %d\n", w.ws_row);
    printf ("columns %d\n", w.ws_col);
    return 0;
}

【讨论】:

    【解决方案2】:

    正如我评论的,你想使用ncurses

    所以安装开发包(在 Debian 上:aptitude install libncurses5-dev),然后:

    1. 添加

      #include  <ncurses.h>
      

      到您的源代码。

    2. 与它链接,即用它编译

      g++ -Wall yourcode.cc -lncurses -o yourprog
      
    3. 调用相应的函数。阅读ncurses programming HowTo

    【讨论】:

    • 为什么不直接用 ioctl 来获取 winsize?
    • 因为一般来说,如果你关心终端,你想在里面写,ncurses 是合适的库。
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 2011-06-06
    • 2017-04-06
    • 1970-01-01
    • 2011-09-29
    • 2013-04-17
    • 2020-08-29
    • 2022-01-09
    相关资源
    最近更新 更多