CodeBlanks Logo Icon CodeBlanks

Summary - Terminal I/O

Combine termios and ANSI to write a terminal app.

Terminal I/O summary

You learned the terminal I/O toolkit: termios for reading settings, raw mode for instant keys, non-blocking for non-waiting reads, ANSI for color and cursor, ioctl for size. These are the foundation of interactive apps.

In this summary we will combine termios, fcntl and ioctl into a terminal preparation app. Using them together shows how real CLI tools are built. The output is deterministic: we print a fixed ready message.

Practice Prepare the terminal

Read settings with struct termios t; tcgetattr(STDIN_FILENO, &t);. Switch to non-blocking mode with fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);. Declare struct winsize ws; ws.ws_row = 24; ws.ws_col = 80; and call (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);. Print with printf("terminal ready\n");.

Starter code

main.c
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>

// Read terminal settings
// Switch to non-blocking mode
// Prepare size struct and call ioctl, print ready

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>

int main(void) {
    struct termios t;
    tcgetattr(STDIN_FILENO, &t);
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
    struct winsize ws;
    ws.ws_row = 24;
    ws.ws_col = 80;
    (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
    printf("terminal ready\n");
    return 0;
}

Expected output

terminal ready

Next steps

You completed terminal I/O. These foundations are the core of text editors, shells and TUI apps. With termios and raw mode you get key-by-key input, with ANSI colors, with ioctl the size.

Next topics: dynamic loading for plugin systems and cryptography for security. Combined with terminal apps, they form powerful CLI tools.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool is used for colored output?

  • flock
  • fcntl
  • shmget
  • ANSI escape Correct answer

Explanation: ANSI escape sequences are used for color and formatting.

2 Match terminal tools

Term Meaning
termios Read settings
cfmakeraw Raw mode
O_NONBLOCK Non-blocking
ioctl Size

All lessons in Advanced