I wrote a small console program that requires an occasional clearing of the terminal screen. I wrote the code on/for a *nix system and used system("clear") in these instances. Once my code was complete I reviewed it to assess the portability of my code. The above method of clearing the screen was my only apparent portability issue. I then looked for other possible ways for clearing the terminal and found some documentation on ANSI Cursor Indexing, specifically:
void cls() {
//27 is ESC ASCII char
printf("%c[2J",27); //clears screen
printf("%c[0;0H",27); //sets cursor at [0,0]
}
To my surprise this code worked wonderfully on my *nix system. I was wondering, is this ANSI Cursor Indexing Scheme portable? Will this code compile and behave expectedly on all systems with a C standard compiler?”
ANSI and VT100 escape sequences are very close, which means that if the terminal is either of those two, the set of commands listed above are definitely going to work. Bear in mind however that ANSI is a superset of VT100, so VT100 compatible terminals will NOT understand ALL ANSI sequences.
VT100 terminal emulators are among the absolutely most common ones (including the default for xterm and other “X-windows style shells”.
Clearly, say, a Volker-Craig 404 terminal emulator [does anyone use those? ;)] will NOT understand either ANSI or VT100 escape sequences, or indeed ANY escape sequences.
I would point out also that your code will be simpler by incorporating your ESC into the constant string:
or if you want to make it a little more readable: