可用ioctl读取winsize结构。
结构定义
struct winsize {unsigned short ws_row;unsigned short ws_col;unsigned short ws_xpixel;unsigned short ws_ypixel;};
测试代码
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>int main()
{struct winsize sz; ioctl(STDIN_FILENO, TIOCGWINSZ, &sz);printf("width %d height %d xpixels %d ypixels %d\n",·sz.ws_col,sz.ws_row,sz.ws_xpixel,sz.ws_ypixel); return 0;
}
捕获尺寸变动
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>void szchange(int signum)
{struct winsize sz;ioctl(STDIN_FILENO, TIOCGWINSZ, &sz);printf("width %d height %d\n", sz.ws_col,sz.ws_row);
}
int main()
{signal(SIGWINCH,szchange);while(1)sleep(1);return 0;
}
shell 下 获取
echo $LINES $COLUMNS
$LINES 行数 $COLUMNS列数