Get size of terminal window (rows/columns)

前端 未结 6 2096
执笔经年
执笔经年 2020-12-02 13:37

Is there any reliable way of getting the number of columns/rows of the current output terminal window?

I want to retrieve these numbers in a C/C++ program.

I

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 14:20

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

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

提交回复
热议问题