为了账号安全,请及时绑定邮箱和手机立即绑定

用C来获取终端宽度?

用C来获取终端宽度?

LEATH 2019-07-11 20:58:13
用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;}
查看完整描述

3 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

#include <stdio.h>#include <stdlib.h>#include <termcap.h>#include <error.h>static char termbuf[2048];int main(void){
    char *termtype = getenv("TERM");

    if (tgetent(termbuf, termtype) < 0) {
        error(EXIT_FAILURE, 0, "Could not access the termcap data base.\n");
    }

    int lines = tgetnum("li");
    int columns = tgetnum("co");
    printf("lines = %d; columns = %d.\n", lines, columns);
    return 0;}

需要用-ltermcap..有很多其他有用的信息,你可以使用术语。检查术语手册info termcap更多细节。


查看完整回答
反对 回复 2019-07-11
  • 3 回答
  • 0 关注
  • 860 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信