Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the terminal dimensions in C++ code? [duplicate]

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
}

1 Answers

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;
}
like image 88
4pie0 Avatar answered Jan 24 '26 13:01

4pie0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!