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

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

问题描述

我一直在寻找一种方式,从我的C程序中获取终端的宽度。我一直想出沿着线的东西:

 的#include< SYS / ioctl.h>
#包括LT&;&stdio.h中GT;INT主要(无效)
{
    结构ttysize TS;
    的ioctl(0,TIOCGSIZE,&安培; TS);    输出(线路%d个\\ N,ts.ts_lines);
    的printf(列%d个\\ N,ts.ts_cols);
}

但每次我尝试,我得到

 奥斯汀@:〜$ GCC test.c的-o测试
test.c的:在函数'主':
test.c的:6:错误:TS的存储容量是未知
test.c的:7:错误:TIOCGSIZE'未申报(在一次使用此功能)
test.c的:7:错误:(每个未声明的标识符报道只有一次
test.c的:7:错误:它出现在每个功能)

这是做到这一点的最好办法,还是有更好的办法?如果不是我怎么能得到这个工作?

编辑:固定的code是

 的#include< SYS / ioctl.h>
#包括LT&;&stdio.h中GT;INT主要(无效)
{
    结构使用winsize瓦;
    的ioctl(0,TIOCGWINSZ,&安培; W)    输出(线路%d个\\ N,w.ws_row);
    的printf(列%d个\\ N,w.ws_col);
    返回0;
}


解决方案

你有没有考虑使用的getenv() 的?它可以让你得到包含端子列和行系统的环境变量。

或者使用方法,如果你想看到内核所认为的终端大小(如果终端更好地调整大小),你需要使用TIOCGWINSZ,而不是你的TIOCGSIZE,像这样:

 结构使用winsize瓦;
的ioctl(STDOUT_FILENO,TIOCGWINSZ,&安培; W)

和全code:

 的#include< SYS / ioctl.h>
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;INT主(INT ARGC,字符** argv的)
{
    结构使用winsize瓦;
    的ioctl(STDOUT_FILENO,TIOCGWINSZ,&安培; W)    输出(线路%d个\\ N,w.ws_row);
    的printf(列%d个\\ N,w.ws_col);
    返回0; //确保主返回int
}

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

But everytime I try that I get

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?

EDIT: fixed code is

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

解决方案

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

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);

and the full code:

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

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

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