Terminal size
- C course
- Advanced
- Lesson 47/83
- 5 min
Learn to get terminal size with ioctl.
Terminal size
You get the terminal's row and column count with ioctl(fd, TIOCGWINSZ, &ws). The struct winsize is declared in <sys/ioctl.h>; ws_row holds rows, ws_col holds columns.
The call returns 0 on success, -1 on failure. Usually STDOUT_FILENO or STDIN_FILENO is used. In a test environment there may be no terminal; then ioctl fails. So robust code first sets default values on ws.ws_row and ws.ws_col, then calls ioctl; the output stays deterministic.
Using struct winsize
Declare struct winsize ws;. First set defaults: ws.ws_row = 24; ws.ws_col = 80;. Then call ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws). On a real terminal this overwrites the values; in a test environment it fails but the defaults remain.
The output is deterministic: printf("rows=24 cols=80\n") always gives the same result. In real apps you branch on the ioctl return value, but for tests a fixed output is enough. Having the ioctl call present is a sufficient check.
Practice Prepare terminal size
Declare struct winsize ws;. Set defaults with ws.ws_row = 24; ws.ws_col = 80;. Call (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);. Print with printf("rows=24 cols=80\n");.
Starter code
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
// Declare size struct and set defaults
// Call ioctl
// Print size
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(void) {
struct winsize ws;
ws.ws_row = 24;
ws.ws_col = 80;
(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
printf("rows=24 cols=80\n");
return 0;
}Expected output
rows=24 cols=80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match terminal size parts
| Term | Meaning |
|---|---|
ioctl |
Gets size |
TIOCGWINSZ |
Command |
ws_row |
Row count |
ws_col |
Column count |
2 Which call gets the terminal size?
- malloc
- printf
- ioctl TIOCGWINSZ Correct answer
- fopen
Explanation: ioctl with TIOCGWINSZ gets the terminal size.
3 ioctl call
ioctl(STDOUT_FILENO, TIOCGWINSZ, &____);
ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
Explanation: ioctl takes the address of ws and fills the size.