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\n", max.ws_row);
printf ("columns %d\n", 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.
The below two functions will get the window size somewhat more directly.
Note that I found, using gcc, that neither this approach nor GetConsoleScreenBufferInfo works if the program is piped. That is somewhat of a pain as for/f then does not work either. Apparently the screen data is not available in a pipe.
Um, the above remark is of course enormously stupid. ;) It is STDOUT that is not the screen in a pipe! That does mean I prefer using STD_ERROR_HANDLE above STD_OUTPUT_HANDLE. I am far less likely to direct standard error away from the screen than standard output.
This prints the size of the console, not the buffer:
This code works because
srWindow
"contains the console screen buffer coordinates of the upper-left and lower-right corners of the display window", and theSMALL_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 got1
less than the actual value, I added one.(Partial answer)
This code:
Gives the size of the buffer. The only problem is that
dwSize.Y
is not really the size of the screen (300 here instead of 25 lines). ButdwSize.X
matches the column's number. Needs onlywindows.h
to work.