I\'ve been looking for a way to get the terminal width from within my C program. What I keep coming up with is something along the lines of:
#include
Here are the function calls for the already suggested environmental variable thing:
int lines = atoi(getenv("LINES"));
int columns = atoi(getenv("COLUMNS"));
Have you considered using getenv() ? It allows you to get the system's environment variables which contain the terminals columns and lines.
Alternatively using your method, if you want 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);
and the full 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
}