c - 在C中获取终端宽度?

我一直在寻找一种从我的 C 程序中获取终端宽度的方法。我一直想出的东西是这样的:

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

int main (void)
{
    struct ttysize ts;
    ioctl(0, TIOCGSIZE, &ts);

    printf ("lines %d\n", ts.ts_lines);
    printf ("columns %d\n", ts.ts_cols);
}

但每次我尝试都会得到

austin@:~$ gcc test.c -o test
test.c: In function ‘main’:
test.c:6: error: storage size of ‘ts’ isn’t known
test.c:7: error: ‘TIOCGSIZE’ undeclared (first use in this function)
test.c:7: error: (Each undeclared identifier is reported only once
test.c:7: error: for each function it appears in.)

这是最好的方法,还是有更好的方法?如果不是,我怎样才能让它工作?

编辑:固定代码是

#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;
}

最佳答案

您是否考虑过使用 getenv() ?它允许您获取包含终端列和行的系统环境变量。

或者使用您的方法,如果您想查看内核看到的终端大小(如果终端调整大小更好),您需要使用 TIOCGWINSZ,而不是您的 TIOCGSIZE,如下所示:

struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

以及完整的代码:

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

int main (int argc, char **argv)
{
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

    printf ("lines %d\n", w.ws_row);
    printf ("columns %d\n", w.ws_col);
    return 0;  // make sure your main returns int
}

https://stackoverflow.com/questions/1022957/

相关文章:

linux - 为什么在 Bash 中应该避免使用 eval,我应该使用什么来代替?

linux - 如何计算每个目录中的文件数?

android - Ubuntu - 错误 : Failed to create the SD ca

python - Python中的字符串如何格式化 boolean 值?

Linux - 替换文件名中的空格

python - 在 python 中创建线程

python - 如何在 Python 中比较对象的类型?

python - 导入语句python3的变化

linux - 如何获取 Docker 中依赖的子镜像列表?

python - 如何使用 Python 发送电子邮件?