Cで端末の幅を取得しますか?

getenv() の使用を検討しましたか?端末の列と行を含むシステムの環境変数を取得できます。

別の方法を使用して、カーネルが端末のサイズとして認識しているものを確認したい場合 (端末のサイズが変更された場合に適しています)、TIOCGSIZE ではなく、TIOCGWINSZ を使用する必要があります。

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
}

この例は少し長いですが、端末の寸法を検出する最も移植性の高い方法だと思います。これはサイズ変更イベントも処理します。

tim と rlbond が示唆するように、私は ncurses を使用しています。環境変数を直接読み取る場合と比較して、端末の互換性が大幅に向上することが保証されます。

#include <ncurses.h>
#include <string.h>
#include <signal.h>

// SIGWINCH is called when the window is resized.
void handle_winch(int sig){
  signal(SIGWINCH, SIG_IGN);

  // Reinitialize the window to update data structures.
  endwin();
  initscr();
  refresh();
  clear();

  char tmp[128];
  sprintf(tmp, "%dx%d", COLS, LINES);

  // Approximate the center
  int x = COLS / 2 - strlen(tmp) / 2;
  int y = LINES / 2 - 1;

  mvaddstr(y, x, tmp);
  refresh();

  signal(SIGWINCH, handle_winch);
}

int main(int argc, char *argv[]){
  initscr();
  // COLS/LINES are now set

  signal(SIGWINCH, handle_winch);

  while(getch() != 27){
    /* Nada */
  }

  endwin();

  return(0);
}

#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <error.h>

static char termbuf[2048];

int main(void)
{
    char *termtype = getenv("TERM");

    if (tgetent(termbuf, termtype) < 0) {
        error(EXIT_FAILURE, 0, "Could not access the termcap data base.\n");
    }

    int lines = tgetnum("li");
    int columns = tgetnum("co");
    printf("lines = %d; columns = %d.\n", lines, columns);
    return 0;
}

-ltermcap でコンパイルする必要があります . termcap を使用して取得できるその他の有用な情報が多数あります。 info termcap を使用して termcap のマニュアルを確認してください 詳細はこちら