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


LEATH
浏览 868回答 3
3回答

慕丝7291255

#include&nbsp;<stdio.h>#include&nbsp;<stdlib.h>#include&nbsp;<termcap.h>#include&nbsp;<error.h>static&nbsp;char&nbsp;termbuf[2048];int&nbsp;main(void){ &nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;*termtype&nbsp;=&nbsp;getenv("TERM"); &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(tgetent(termbuf,&nbsp;termtype)&nbsp;<&nbsp;0)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error(EXIT_FAILURE,&nbsp;0,&nbsp;"Could&nbsp;not&nbsp;access&nbsp;the&nbsp;termcap&nbsp;data&nbsp;base.\n"); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;lines&nbsp;=&nbsp;tgetnum("li"); &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;columns&nbsp;=&nbsp;tgetnum("co"); &nbsp;&nbsp;&nbsp;&nbsp;printf("lines&nbsp;=&nbsp;%d;&nbsp;columns&nbsp;=&nbsp;%d.\n",&nbsp;lines,&nbsp;columns); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;0;}需要用-ltermcap..有很多其他有用的信息,你可以使用术语。检查术语手册info termcap更多细节。
打开App,查看更多内容
随时随地看视频慕课网APP