gpt4 book ai didi

c - 在 Unix/Linux 上用 C 动态确定终端高度的最佳方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:34 25 4
gpt4 key购买 nike

我想每隔 X 行显示一个标题,其中 X 使标题显示为最后一个滚动屏幕。用户可以改变终端尺寸,程序应该知道答案。大致类似

i = get_lines()+1;
while (1) {
if (i > get_lines()) {
printf("header");
i = 0;
} else {
i++;
}
do_stuff();
}

最佳答案

您可以使用 TIOCGWINSZ 读取当前终端高度:

#include <sys/ioctl.h> /* needed for lines */
#include <signal.h> /* needed for lines */
#include <stdio.h> /* needed for printf */
#include <time.h> /* needed for sleep */

unsigned short lines;
static void get_lines(int signo) {
struct winsize ws;
ioctl(fileno(stdout), TIOCGWINSZ, &ws);
lines = ws.ws_row;
}

int main(int argc, char** argv) {
int i;
struct timespec ts;

get_lines(SIGWINCH);
signal(SIGWINCH, get_lines);

i = lines;
while (1) {
if (i >= lines) {
printf("header\n");
i = 3; /* 3 not 1 because header + last empty line */
} else {
i++;
}
printf("line\n");
ts.tv_sec = 0;
ts.tv_nsec = 500000000;
nanosleep(&ts, NULL);
}
}

行数现在在 ws.ws_row 中。

当用户更改终端大小时(即调整终端窗口的大小),SIGWINCH 会发送到前台进程。因此,您应该为该事件建立一个信号处理程序并重新读取窗口大小。

关于c - 在 Unix/Linux 上用 C 动态确定终端高度的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43231764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com