linux - [Solved-5 Solutions] Getting terminal width in C ? - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to get terminal width in C ?

Linux - Solution 1:

Using getenv() : It allows to get the system's environment variables which contain the terminals columns and lines.

Alternatively using your method, if you need to see what the kernel sees as the terminal size (better in case terminal is resized), you would need to use TIOCGWINSZ, as opposed to your TIOCGSIZE, like so:

struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
click below button to copy the code. By - Linux tutorial - team

Code:

#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
}
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 2:

It's the most portable way of detecting the terminal dimensions. This also handles resize events.

#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);
}
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

#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;
}
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

If you have ncurses installed and are using it, you can use getmaxyx() to find the dimensions of the terminal.

Linux - Solution 5:

Here are the function calls for the environmental variable thing:

int lines = atoi(getenv("LINES"));
int columns = atoi(getenv("COLUMNS"));
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - Getting terminal width in C ?