iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🖥️

Notes on Terminal Width and Height

に公開

Getting Terminal Width and Height

You can get the window size by passing TIOCGWINSZ to ioctl(2).

#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>

int main(void)
{
  struct winsize ws;
  if (~ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)) {
    printf("(%d, %d)\n", ws.ws_col, ws.ws_row);  // (width, height)
  }
  else {
    perror("ioctl");
  }
  return 0;
}

Knowing When the Terminal Width and Height Change

You can catch the SIGWINCH signal.
(Note: Using signal(2) seems to be deprecated.)

#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static void winch_handler(int);

int main(int argc, char *argv[])
{
  struct winsize ws;
  struct sigaction act;

  winch_handler(0);    // Initial display

  act.sa_handler = winch_handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags= SA_RESTART;
  if (sigaction(SIGWINCH, &act, NULL) < 0) {
    perror("sigaction");
    exit(EXIT_FAILURE);
  }

  while (1) {
    sleep(1);
  }

  return 0;
}

void winch_handler(int sig)
{
  struct winsize ws;

  if (~ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)) {
    printf("(%d, %d)\n", ws.ws_col, ws.ws_row);  // (width, height)
  }
  else {
    perror("ioctl");
  }
}

Operation image


References

Discussion