Confused with interesting printf() statement
c, printf
Solution
This doesn't really have anything to do with `printf`. The C11 standard lists escape sequences in §5.2.2, and the list consists of `\a`, `\b`, `\f`, `\n`, `\r`, `\t` and `\v`. As an extension, GCC considers `\e` to be an escape sequence which stands for the ASCII character Esc (`\E` may work as well, or your compiler may support neither of them. Consult the documentation for your compiler). What follows are non-portable control sequences. They are not guaranteed to work the same in all terminals, or even work at all. The best way to know is to consult the documentation for your system.
§6.4.4.4 also describes octal escape sequences. For example, `\033`, where `033` is `27` in decimal, and therefore the escape character in ASCII. Similarly, you can use `\x1b`, which is a hexadecimal escape sequence specifying the same character.
If we inspect the output of the program with `od -c`, it shows `033`.
(✿´‿`) ~/test> ./a.out | od -c
0000000 033 [ 0 m 033 [ ? 2 5 l 033 [ 2 J
0000016
The ANSI escape sequences are interpreted by terminal emulators. C will convert the octal/hexadecimal escape sequences to the ASCII Esc character. Your compiler, as an extension, might also convert `\e` or `\E`. As requested, a brief explanation of what the control sequences are doing:
- `[0m`: resets all the SGR attributes
- `[?25l`: hides the cursor
`[2J`: from Wikipedia:
Clears part of the screen. If `n` is 0 (or missing), clear from cursor to end of screen. If `n` is 1, clear from cursor to beginning of the screen. If `n` is 2, clear entire screen ...
Problem
By reading this code, I stumbled upon the following `printf()` statement: ``` // reset, hide cursor and clear screen printf("\e[0m\e[?25l\e[2J"); ``` I must admit that I am not a fully qualified C hacker and do not fully understand this. I tweaked around, removing the arguments, and I understand what it does (well, the comment actually says it all), but I have no idea how it's done. Also, this is something kind of hard to google for. How does this `printf()` call work?