6

Possible Duplicate:
Getting terminal width in C?

On Linux and OS X, my shell reports $COLUMNS has the width of the terminal window -- and resizing the window will adjust this shell variable.

But in my C/C++ program, getenv("COLUMNS") doesn't seem to find the variable.

Anybody have an explanation? Or an alternate suggestion for letting my C++ program figure out the width of the terminal it's running in (for some help message word wrapping)?

Community
  • 1
  • 1
Larry Gritz
  • 13,331
  • 5
  • 42
  • 42

1 Answers1

11

Perhaps something like this:

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

int main()
{
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);

    printf("lines %d\n", w.ws_row);
    printf("columns %d\n", w.ws_col);
    return 0;
}

Taken straight from: Getting terminal width in C?

Community
  • 1
  • 1
LainIwakura
  • 2,871
  • 2
  • 19
  • 22