Clear console screen in Windows and Linux


In case of develop of a console mode application it could be quite frequently to clear all the console screen for prepare new output. Here some examples of codes for clear screen in both operating systems.




Code for Windows

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD ConsoleSize, CharsWritten;
COORD OriginCoord = {0,0};

GetConsoleScreenBufferInfo(hConsole, &csbi);

ConsoleSize = (csbi.dwSize.X * csbi.dwSize.Y);

FillConsoleOutputCharacter(hConsole, static_cast<TCHAR>(' '), ConsoleSize, OriginCoord, &CharsWritten);

GetConsoleScreenBufferInfo(hConsole, &csbi);

FillConsoleOutputAttribute(hConsole, csbi.wAttributes, ConsoleSize, OriginCoord, &CharsWritten);

Code for Linux (please note this code will work only in ANSI compatible terminals)

printf("\033[2J");

Another "universal" way to clear the screen in console mode could be to print a new line character (\n) for a number equal to the number of lines available. This will "move" up all the current console content out of the visible part of the screen. Not very elegant solution but will work in each console mode system.

Comments

Post a Comment

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model