Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

console - Getting terminal size in c for windows?

How to check ymax and xmax in a console window, under Windows, using plain c?

There is this piece of code for linux:

#include <stdio.h>
#include <sys/ioctl.h>
int main (void)
{
    struct winsize max;
    ioctl(0, TIOCGWINSZ , &max);
    printf ("lines %d
", max.ws_row);
    printf ("columns %d
", max.ws_col);
}

Now I wonder how can I do the same for windows. I tried winioctl.h but it does not define struct winsize nor any other with a similar name.

Any tips? Thanks.

PS. In linux you also can find the console size using getenv("LINES");. Is there a similar variable under windows?

PPS. Also, there is always ncurses.h, that I suppose work both systems, but I'm avoiding it because of conflicts with other libraries I have.

PPPS. This question here Getting terminal width in C? has a lot of tips, so no need to repeat that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This prints the size of the console, not the buffer:

#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
", columns);
    printf("rows: %d
", rows);
    return 0;
}

This code works because srWindow "contains the console screen buffer coordinates of the upper-left and lower-right corners of the display window", and the SMALL_RECT structure "specify the rows and columns of screen-buffer character cells" according to MSDN. I subtracted the parallel sides to get the size of the console window. Since I got 1 less than the actual value, I added one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...