我一直在寻找一种从我的 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() ?它允许您获取包含终端列和行的系统环境变量。
或者使用您的方法,如果您想查看内核看到的终端大小(如果终端调整大小更好),您需要使用 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
}
https://stackoverflow.com/questions/1022957/