How to clear console screen the proper way.
Language Agnostic Clearing of Console Screen: Without clear() or cls()
To cut it short: I had often heard of people asking how to properly clear the screen, and no one seems to know what to use other than calling a system function, or they suggest a library such as ncurses to handle screen formatting. We can leave this to ANSI as we had for many years.
What about ANSI? Does your modern computer even support ANSI? The answer: Yes.
Windows has a nice ansi.sys, Linux terminals accept ANSI without trouble, OSX has some ANSI support in terminal emulators.
ANSI stands for American National Standard Intitution. The ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII, is more properly referred to as Windows-1252 (mostly on Western systems, it can represent specific other Windows code pages on other systems). This is essentially an extension of the ASCII character set in that it includes all the ASCII characters with an additional 127 character codes, being an 8-bit encoding.
Within the ANSI standard, there lays an escape ESC character: ASCII decimal 27/hex 0x1B/octal 033 which can take care of formatting, colouring and alike with escape sequences. Here we will be using the ESC character to format and clear the screen.
-----------------------------------------------------------------------------------
Examples:
First a simple example to show you how an escape works, would be to colour the text: 'Hello CodeCall':
printf("Hello %c[32mCodeCall!", (char) 27);
The escape sequence in this case is [32m for green.
For a list of escape codes including what we will use, can be found here:
ASCII Table - ANSI Escape sequences (ANSI Escape codes) - VT100 / VT52
Clearing of screen:
The following escape sequence clears all characters above and below the cursor location: [2J and this sets cursor position to 0,0: [;H .
A sample call in another language, such as PHP in CLI mode:
<?php print str_repeat("--=-------======------======-----=\n\n", 1024); print chr(27) . "[2J" . chr(27) . "[;H"; print "I am at cursor position 0,0 on a clean screen."; ?>Or in Java:
public class ansiclrscr { public static void main(String[] argv) { System.out.print("foo\nbar\nbaz\nquux"); System.out.print("\033[2J\033[;H"); System.out.print( "I am at cursor position 0,0 on a clean screen."); } }
This may be the best way depending on implementation, as it is standards-conforming and is widely supported on most platforms, allowing console formatting without the need of an external library.
Cleaning up:
After any attributes have been set, such as colour, the console can be reset with the following attribute:
\033[0m
(Thanks: Dargueta.)
Edited by Alexander, 23 July 2014 - 06:09 AM.