在 C 中获取终端宽度? [英] Getting terminal width in C?

查看:33
本文介绍了在 C 中获取终端宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been looking for a way to get the terminal width from within my C program. What I keep coming up with is something along the lines of:

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

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

    printf ("lines %d
", ts.ts_lines);
    printf ("columns %d
", 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.)

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

Is this the best way to do this, or is there a better way? If not how can I get this to work?

固定代码是

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

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

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

推荐答案

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

Have you considered using getenv() ? It allows you to get the system's environment variables which contain the terminals columns and lines.

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

Alternatively using your method, if you want to see what the kernel sees as the terminal size (better in case terminal is resized), you would need to use TIOCGWINSZ, as opposed to your TIOCGSIZE, like so:

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
", w.ws_row);
    printf ("columns %d
", w.ws_col);
    return 0;  // make sure your main returns int
}

这篇关于在 C 中获取终端宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆