How to clear the screen with \x1b[2j?

The standard C library doesn't provide a way of clearing the screen. You need an operating-system-dependent library for that.

Under DOS and Windows, for a program running in a DOS or Windows console, you can use the DOS/Windows extensions provided in the core C library shipped with the OS:

#include <conio.h>
clrscr();

Under unix systems, you can use the curses library, which is provided with the OS. Ports of the curses library exist for most operating systems, including Windows, so this is the way to go in a portable program. Link your program with -lcurses and use

#include <curses.h>
erase();

Some terminals and terminal emulators perform special functions such as clearing the screen when they receive an escape sequence. Most terminals follow the ANSI standard which defines a number of escape sequences; "\x1b[2J" is such a sequence, and its effect is to clear the screen. Note the capital J. On such a terminal, fputs("\x1b[2J", stdout) clears the screen. This is in fact what the curses library does when you call erase() on such a terminal; the curses library includes a database of terminal types and what escape sequences to use on the various types.


If you're confident that is the control sequence you need to use, then:

#include <stdio.h>

int main(void)
{
    fputs("\x1b[2j", stdout);
    return(0);
}

This deliberately omits the newline - but you might be better off with adding one after the 'j'. However, as Gilles points out in his answer, there are other ways to do it which have merits compared with this solution.

Tags:

C