我一直在寻找一种方法,在我的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;
}
LINES
和COLUMNS
变量,但它们似乎没有被导出。因此无法从您的C程序中访问。 - Alexis Wilkegetenv("COLUMNS")
完美地工作时,我的下巴都要掉下来了。所以现在我有一组备选方案,全部来自于TIOCWINSZ
ioctl,如果不是tty,则使用getenv,最后使用经典的ANSI转义“将光标移动到9999,9999并查询光标位置”。最后一个适用于嵌入式系统的串行控制台 :) - troglobit