I've read that \x1b
represents the escape character, but isn't '\'
by itself the escape character? A tutorial wants me to write
write(STDOUT_FILENO, "\x1b[2J", 4);
to clear the screen. Why won't '\[2J'
do the job?
I've read that \x1b
represents the escape character, but isn't '\'
by itself the escape character? A tutorial wants me to write
write(STDOUT_FILENO, "\x1b[2J", 4);
to clear the screen. Why won't '\[2J'
do the job?
Although this question is a bit old, I'll give my two cents using the \n
as an example.
Although the ASCII escape character
is \x1B
, and n
is \x6E
, it's not possible to insert a \n
character into a string using \x1B\x6E
, for two reasons:
The ESC
character in ASCII table, and the escape character \
in programming languages are two different things.
Programming languages search for \n
(as a single entity), in the source code (before we're in bytes level) to convert it into line-feed bytes, so \x1B\x6E
will not get converted to anything. Thus, even if you use \x5C\x6E
in the source code(an ASCII \
and an ASCII n
), it won't get converted to a line-feed.
Example in Python:
>>> print("Hello\x5C\x6EWorld")
Hello\nWorld
# if one still insists on inserting a new line using an ascii line-feed (\x0A), they can do:
>>> print("Hello\x0AWorld")
Hello
World
HTH.
To elaborate the comments of Ken and Jonathan a bit: Escaping here is a general concept. It basically implies the change of something's interpretation.
The escape character in ASCII originates from teletype machines, where the appearance of ESC has changed the interpretation of the following character. It is used in the same way by many terminals. E.g., the appearance of ESC before the string [2J
cause the the string (i.e. the characters [
,2
, and J
) aren't displayed at the terminal, but interpreted as the command "clear entire screen". Thus, the escape character has changed the interpretation mode.
However, there is no straightforward way to enter the ASCII escape character (because pressing there ESC key at your keyboard usually changes a mode in your editor, terminal or whatever), and even if you could, the allowed character set of the language C doesn't include it. Now, you need a second level of escaping: C has its own character for escaping: \
. It changes the meaning of the next character(s). E.g., a precedent backslash changes the meaning (interpretation) of the following character n
into newline. In addition, the \x
(or \0
, respectively) let the C parser interpret the following two (three) characters as hexadecimal (octal) number - instead as the characters themselves - and insert the character that corresponds to that very code number. Since the ASCII code for escape has the number 27 (decimal), or 1b (hexadecimal), or 33 (octal), respectively, you generate the ASCII escape character in C by \x1b
or \033
.
With other words, you escape in C with \
to generate the ASCII escape character, that in turn forces an escaping at your terminal.