I was looking for a way to "reset" my Unix terminal window after closing my program, and stumbled upon printf("\033c" );
which works perfectly, but I just can't understand it. I went to man console_codes
and since I'm somewhat inexperienced with Unix c programming, it wasn't very helpful.
Could someone explain printf("\033c" );
?
In C numbers starting with a leading zero are octal numbers. Numbers in base 8.
What it does is print the character represented by octal number
33
followed by a'c'
.In ASCII encoding the octal number
33
is theESC
(escape) character, which is a common prefix for terminal control sequences.With that knowledge searching for terminal control sequences we can find e.g. this VT100 control sequence reference (VT100 was an old "dumb" terminal, and is emulated by most modern terminal programs). Using the VT100 reference we find
<ESC>c
in the terminal setup section, where it's documented asThe
ESC
character could also be printed using"\x1b"
(still assuming ASCII encoding). There is no way to use decimal numbers in constant string literals, only octal and hexadecimal.However (as noted by the commend by chux) the sequence
"\x1bc"
will not do the same as"\033c"
. That's because0x1bc
is a valid hexadecimal number, and the compiler is greedy when it parses such sequences. It will print the character represented by the value0x1bc
instead, and I have no idea what it might be (depends on locale and terminal settings I suppose, might be prited as a Unicode character).That's an escape sequence used to reset a DEC VT100 (or compatible) terminal. Some terminals (such as Linux console) accept VT100-style escape sequences, even when they are not actually VT100s.
The
\033
is the ASCII escape character, which begins these sequences. Most are followed by another special character (this is a rare exception). XTerm Control Sequences lists that, along with others that are not followed by a special character.In ECMA-48 it is possible to use a different character for the usual case, e.g.,
[
for the *control sequence initiator.Resetting a real VT100 (in contrast to a terminal emulator) does more than clear the screen, as noted in Debian Bug report logs - #60377 "reset" broken for dumb terminals, but users of terminal emulators tend to assume it is a short way to clear the screen. The standard way would be something like this:
The ncurses FAQ Why does reset log me out? addresses that issue.
Incidentally, users of terminal emulators also get other issues with the terminal confused. The ncurses FAQ How do I get color with VT100? addresses one of those.
It clears the screen in Linux type operating systems (ubuntu, fedora etc...). You can check the ASCII table here. Under octa 33 (decimal 27) you have ESC character. http://www.asciitable.com/index/asciifull.gif