我一直在寻找一种从 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() http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html?它允许您获取包含终端列和行的系统环境变量。
或者使用您的方法,如果您想查看内核所看到的终端大小(如果调整终端大小则更好),您需要使用 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)