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

How do we implement clrscr() ? As a result, I found that \x1b[2j can be used to clean the screen, but how do we use it?

+6
c
source share
3 answers

The C standard library does not provide a way to clear the screen. To do this, you need a library that depends on the operating system.

On DOS and Windows, for a program running in the DOS or Windows console, you can use the DOS / Windows extensions provided in the main C library supplied with the OS:

 #include <conio.h> clrscr(); 

On Unix systems, you can use the curses library, which is provided with the OS. Curse library ports exist for most operating systems, including Windows, so this is the way to the portable program. Associate 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 comply with the ANSI standard, which defines several escape sequences; "\x1b[2J" is such a sequence, and its effect is to clear the screen. Pay attention to capital J On such a terminal, fputs("\x1b[2J", stdout) clears the screen. This is what the curses library does when you call erase() on such a terminal; The curses library includes a database of terminal types and which escape sequences to use on different types.

+5
source share

If you are sure that this is the escape sequence that you should use, then:

 #include <stdio.h> int main(void) { fputs("\x1b[2j", stdout); return(0); } 

This intentionally excludes a new line - but you might be better off adding one after "j". However, as Gilles points out in the answer, there are other ways to do this that have advantages over this solution.

+2
source share

On Windows you can try

 #include <tchar.h> #include <stdio.h> #include <windows.h> void clrscr(void) { HANDLE std_out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO cbi; COORD origin = {0,0}; int buf_length; GetConsoleScreenBufferInfo(std_out,&cbi); buf_length = cbi.dwSize.X*cbi.dwSize.Y; FillConsoleOutputCharacter(std_out,0x20,buf_length,origin,0); FillConsoleOutputAttribute(std_out,0x07,buf_length,origin,0); } int _tmain(int argc, wchar_t *argv[], wchar_t *envp[]) { DWORD i; _tprintf(TEXT("Clear screen probe...\n")); clrscr(); return 0; } 

"\ x1b [H \ x1b [2J" works on OSX.

0
source share

All Articles