10

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 it clear buffer in output stream or does it clear only tty buffers?.

int main()
{
   printf("\033[H\033[J");
   return 0;
}
J...S
  • 5,079
  • 1
  • 20
  • 35

2 Answers2

19

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.

J...S
  • 5,079
  • 1
  • 20
  • 35
6

If I am not mistaken, it makes use of ANSI/VT100 Terminal Control Escape Sequences.

\033 - ASCII escape character

[H - move the cursor to the home position

[J - erases the screen from the current line down to the bottom of the screen

However, this command may not be compatible in every terminal/console.

Whooper
  • 575
  • 4
  • 20
  • But it gives [this](https://i.stack.imgur.com/1u7lj.png) to me . – Maifee Ul Asad Apr 14 '19 at 07:07
  • @MaifeeUlAsad You're using some kind of broken terminal that doesn't support control sequences at all. What IDE is this? –  Apr 14 '19 at 07:09
  • I am using codeblocks - it beeps bro.. – Maifee Ul Asad Apr 14 '19 at 07:10
  • 2
    @MaifeeUlAsad It won't work in Codeblocks it seems. I had tried it earlier as well. But it does on most linux systems. – J...S Apr 14 '19 at 07:11
  • **sad nibba hours** – Maifee Ul Asad Apr 14 '19 at 07:11
  • @MaifeeUlAsad Windows 10 console supports ANSI escape codes but **it's disabled by default**. You need to enable ANSI sequence support by creating a DWORD named `VirtualTerminalLevel` in `HKEY_CURRENT_USER\Console` and set its value to 1 https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences or better move to [Windows terminal](https://github.com/microsoft/terminal). [How to make win32 console recognize ANSI/VT100 escape sequences?](https://stackoverflow.com/q/16755142/995714), [Windows console with ANSI colors handling](https://superuser.com/q/413073/241386) – phuclv Aug 05 '20 at 02:10
  • link that works for ANSI/VT100 Terminal Control Escape Sequences. is https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm – tobi delbruck Feb 21 '23 at 06:53