ANSI escape
- C course
- Advanced
- Lesson 46/83
- 5 min
Learn colors and cursor with ANSI escape sequences.
ANSI escape sequences
ANSI escape sequences are used in terminals for colors, cursor position and style. They all start with ESC (decimal 27, octal \033); then [ and the command. For example \033[31m makes text red, \033[0m resets all formatting.
Color codes: 30 black, 31 red, 32 green, 33 yellow, 34 blue. Cursor movement: \033[H goes to top-left, \033[2J clears the screen. In C you print with printf("\033[31mred\033[0m\n"). In a test environment the ESC character is invisible but the output is deterministic.
Color and reset
The basic method of using color: turn on, write, reset. First turn on the color with \033[31m, write the text, then reset formatting with \033[0m. Otherwise all subsequent output stays colored.
In C you can do this in a single printf: printf("\033[31mred\033[0m\n");. Here \033 produces the ESC character, \n a new line. In a test environment this output contains the ESC character; the expected output uses \u001b for it. The output is deterministic.
Practice Print colored text
Print text in red with printf("\033[31mred\033[0m\n");. Reset with \033[0m after the color code.
Starter code
#include <stdio.h>
// Print red text and reset
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
printf("\033[31mred\033[0m\n");
return 0;
}Expected output
[31mred[0m
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which ANSI code gives red color?
- 30
- 31 Correct answer
- 33
- 32
Explanation: 31 is the code for red color.
2 Match ANSI codes
| Term | Meaning |
|---|---|
\033[31m |
Red |
\033[0m |
Reset |
\033[2J |
Clear screen |
\033[H |
Top-left |
3 Red color
printf("\033[____mred\033[0m
");
printf("\033[31mred\033[0m
");
Explanation: 31 is the ANSI code for red.