Get size of terminal window (rows/columns) Get size of terminal window (rows/columns) shell shell

Get size of terminal window (rows/columns)


On Windows, use the following code to print the size of the console window (borrowed from here):

#include <windows.h>int main(int argc, char *argv[]) {    CONSOLE_SCREEN_BUFFER_INFO csbi;    int columns, rows;    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);    columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;    rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;    printf("columns: %d\n", columns);    printf("rows: %d\n", rows);    return 0;}

On Linux, use the following instead (borrowed from here):

#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}


For Unix(-based), use ioctl(2) and TIOCGWINSZ:

#include <sys/ioctl.h> //ioctl() and TIOCGWINSZ#include <unistd.h> // for STDOUT_FILENO// ...struct winsize size;ioctl(STDOUT_FILENO, TIOCGWINSZ, &size);/* size.ws_row is the number of rows, size.ws_col is the number of columns. */// ...

Also, while I haven't touched Windows in the last five years, GetConsoleScreenBufferInfo() should help you get the console window size.


To expand @herohuyongtao answer for Windows. The .srWindow property gives the answer to the size of the console window, i.e. visible rows and cols. This doesn't say what is the actual available screen buffer width and height, which could be larger if window contains scroll bars. If this is the case, use .dwSize:

CONSOLE_SCREEN_BUFFER_INFO sbInfo;GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbInfo);int availableColumns = sbInfo.dwSize.X;int availableRows = sbInfo.dwSize.Y;