Get Terminal Size in C

Get Terminal Size in C

Terminal dimensions can be useful in command-line interface applications that need to format output according to the available screen space. Examples include text-based interfaces, tables, progress displays, and other console-oriented programs.

There is no single C standard library function that reports the terminal width and height on every operating system. Platform-specific features are therefore required. Windows provides console APIs for reading the current screen buffer information, while Unix-like systems expose terminal dimensions through the ioctl interface.

A portable implementation can hide these differences behind one function:

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/ioctl.h>
#include <unistd.h>
#endif

int get_terminal_size(int *columns, int *rows) {
#ifdef _WIN32
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
        return 1;
    }
    *columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
    *rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
#else
    struct winsize ws;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
        return 1;
    }
    *columns = ws.ws_col;
    *rows = ws.ws_row;
#endif

    return 0;
}

int main(void) {
    int columns;
    int rows;
    if (get_terminal_size(&columns, &rows)) {
        printf("Unable to get terminal size\n");
        return 1;
    }

    printf("Columns: %d\n", columns);
    printf("Rows: %d\n", rows);

    return 0;
}

The program defines the function that provides a common interface for retrieving the number of columns and rows available in the terminal.

On Windows, GetConsoleScreenBufferInfo obtains information about the active console screen buffer. The srWindow member describes the visible console window, and its boundaries are used to calculate the width and height.

For Linux and other Unix-like platforms, ioctl is called with the TIOCGWINSZ request. The resulting winsize structure that contains the terminal dimensions.

Leave a Comment

Cancel reply

Your email address will not be published.