I want to clear the output of my program in C (on terminal/console). I see that most website just use system("cls")
(Windows) or system("clear")
(Linux), but it's not standard and also platform dependant. How can I accomplish that with standard C?
Asked
Active
Viewed 79 times
1
-
6There's nothing in standard C to clear the screen. – Stephen Newell Sep 29 '22 at 03:36
-
`for( int i = 0; i < 10000; i++ ) putchar( '\n');` should do... Don't use this on a hardcopy terminal, though... (Tough job, clearing hardcopy terminal "displays"...) – Fe2O3 Sep 29 '22 at 03:48
-
3"In standard C", there is no guarantee that a terminal window exists in the first place. – Karl Knechtel Sep 29 '22 at 04:06
-
1Clearing an "output" is a question of the specific output device. Are you talking about a terminal? If so, which one? Additionally, this is completely independent of the programming language. The final line is, your question asks the wrong thing. Please clarify. – the busybee Sep 29 '22 at 08:51
-
@thebusybee well, some (old?) languages provided a standard command to clear the screen, like the CLS in basic... – linuxfan says Reinstate Monica Sep 29 '22 at 10:31
-
@linuxfansaysReinstateMonica Such an exception is not a _standard_, it is a specific language on a specific platform. Not all BASIC implementations provide `CLS`. Compared with C, you would need to add, for example, ncurses to C. "Exceptions approve the rule." ;-) – the busybee Sep 29 '22 at 11:32
1 Answers
2
See description of the ANSI clear screen commands here
There are a lot of different ways to use ANSI characters.
#include <stdio.h>
int main()
{
printf("\033[2J");
return 0;
}
Another answer Clearing the screen by printing a character?. Covers a variety of other ANSI codes, see examples there.
How to judge whether stdout supports ANSI escape code is an answer that discusses the ANSI supported terminal in the year 2021 and a method for testing for ANSI support.

atl
- 575
- 3
- 6
-
This is also not particularly portable, as it relies on the terminal supporting ANSI escape codes. – paddy Sep 29 '22 at 03:47
-
Fair point, added a link to answer about how to tell if terminal supports ANSI. – atl Sep 29 '22 at 04:05
-
Worth mentioning the variants `0` and `1` (cursor to top and up to cursor) and the `K` escape (clear line). – David C. Rankin Sep 29 '22 at 04:19
-
agree, lots of ANSI codes available, years ago we used ANSI codes to make an asteroids game on an wyse terminal and 8088 8 bit micro, those were the days! – atl Sep 29 '22 at 04:24
-
-
Maybe, depends on which version. See how and what is supported on their site [Console Virtual Terminal Sequences](https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences). – atl Sep 30 '22 at 01:33