3

I was recently trying to get the size of the terminal in which this program is run.
The problem is that the script + program solution is not handy and it does not support user input or terminal size change.

How can I do that in the C++ code (without messing with the scripts)?
My code:
Bash file (file to be run instead of the C++ program):

cols=`tput cols`
lines=`tput lines`
input="${cols}\n${lines}"
echo -ne "${input}" | [C++ program]

C++ file (the actual program):

#include <iostream>

int main() {
  unsigned lines;
  unsigned cols;
  cin >> cols;
  cin >> lines;
  // some code here
}
4pie0
  • 29,204
  • 9
  • 82
  • 118

2 Answers2

8

As showed in

Getting terminal width in C?

you can get terminal size with ioctl call

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

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

    printf ("lines %d\n", w.ws_row);
    printf ("columns %d\n", w.ws_col);
    return 0;
}
Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
1

As I commented, you want to use ncurses.

So install the development package (on Debian: aptitude install libncurses5-dev), then :

  1. add

    #include  <ncurses.h>
    

    to your source code.

  2. Link with it, i.e. compile with

    g++ -Wall yourcode.cc -lncurses -o yourprog
    
  3. Call the appropriate functions. Read the ncurses programming HowTo

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547