Anonymous user
Terminal control/Dimensions: Difference between revisions
→{{header|C}}: Add solution for Windows.
(Add C using TIOCGWINSZ.) |
(→{{header|C}}: Add solution for Windows.) |
||
Line 6:
C provides no standard way to find the size of a terminal.
=== {{libheader|BSD libc}} ===▼
Some devices can do NAWS (Negotiate About Window Size). A terminal emulator like xterm(1) should set the size. A network server like sshd(1) should copy the size from its client. Other devices, such as plain serial ports, might not know the window size.▼
[[BSD]] systems (and some other [[Unix]] clones) have TIOCGWINSZ. This ioctl(2) call gets the "window size" of a tty(4) device.
▲
▲{{libheader|BSD libc}}
{{works with|OpenBSD|4.9}}
<lang c>#include <sys/ioctl.h> /* ioctl, TIOCGWINSZ */
Line 37:
close(fd);
return 0;
}</lang>
=== [[Windows]] ===
Grab a console screen handle, then call <code>GetConsoleScreenBufferInfo()</code> to get the information. Most consoles have a scroll bar and hold hundreds of lines, but the window shows only 25 or 50 lines. Use the window coordinates to calculate the window size.
{{works with|MinGW}}
<lang c>#include <windows.h>
#include <wchar.h>
int
main()
{
HANDLE console;
CONSOLE_SCREEN_BUFFER_INFO info;
short rows;
short columns;
/* Create a handle to the console screen. */
console = CreateFileW(L"CONOUT$",
GENERIC_READ | GENERIC_WRITE, 0, 0, 0, 0, NULL);
if (console == INVALID_HANDLE_VALUE)
return 1;
/* Calculate the size of the console window. */
if (GetConsoleScreenBufferInfo(console, &info) == 0)
return 1;
CloseHandle(console);
columns = info.srWindow.Right - info.srWindow.Left + 1;
rows = info.srWindow.Bottom - info.srWindow.Top + 1;
wprintf(L"%d columns by %d rows\n", columns, rows);
return 0;
}</lang>
|