What does printf("\033[H\033[J") do in C?

ansi-escape, c

Solution

These are ANSI escape codes.

`\033` stands for `ESC` (ANSI value 27).

ESC [ is a kind of escape sequence called Control Sequence Introducer (CSI).

CSI commands starts with `ESC[` followed by zero or more parameters.

`\033[H` (ie, `ESC[H`) and `\033[J` are CSI codes.

`\033[H` moves the cursor to the top left corner of the screen (ie, the first column of the first row in the screen).

and

`\033[J` clears the part of the screen from the cursor to the end of the screen.

When used in combination, it results in the screen getting cleared with cursor positioned at the beginning of the screen.

This is the functionality that you get when using Ctrl+L or `clear` command on bash.

These CSI can have parameters as well. If none are provided, it will use the default values.

Problem

I have gone through the below strange sequence of characters in some random website. When compiled and executed, this sequence cleared all previous content in terminal. Does this clear the `stdout` buffer or only the `tty` buffers? ``` int main() { printf("\033[H\033[J"); return 0; } ```

Original source

Related problems