Is there a "proper" way to clear the console window in C, besides using system("cls")
?
-
http://www.cplusplus.com/forum/articles/10515/ contains some codes. Although not portable for both Windows and POSIX systems it can be useful for anyone reading this question in future. – Aseem Bansal Jun 22 '13 at 16:02
-
1Also here http://www.cplusplus.com/articles/4z18T05o/ – Marcello Romani Jun 27 '13 at 06:36
-
Nobody has mentioned the standard ASCII control FF (form feed) which ejects a page on printers or printing terminals (such as vt100). – stark Nov 08 '22 at 13:02
14 Answers
printf("\e[1;1H\e[2J");
This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.
#include <unistd.h>
void clearScreen()
{
const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}
There are some other alternatives, some of which don't move the cursor to {1,1}.

- 7,860
- 7
- 40
- 71

- 551
- 4
- 4
-
1Just to let you know, FWIW, this sequence as is didn't work for me in a windows cmd.exe console. – dodgy_coder Apr 09 '13 at 07:56
-
-
1How does it demand POSIX? I don't believe those escape sequences are specified by the POSIX standard. – Keith Thompson May 31 '15 at 21:53
-
That doesn't work for me. What *does* work for me, though, is plain old `"\e[2J"`. I know it's been like four years, but... Care to explain the difference? Or what the `"\e[1;1H"` is supposed to do? – Braden Best Sep 18 '15 at 23:31
-
-
Using [this](https://stackoverflow.com/a/1348624/1429450) I didn't get ISO compatibility errors: `\033[2J\033[1;1H` – Geremia Jan 21 '17 at 20:30
-
Windows' command prompt (Windows 98 through Windows 7) does not support ANSI escapes. It seems that they do in Windows 10 and so presumably Windows 8 as noted by QPaysTaxes. – MD XF Sep 27 '17 at 01:51
-
Nit: Don't use `printf(string);`, use `puts(string);` instead. The former may have UB if `string` contains a percent sign (even though that is not the case here, I recommend making it a habit). – Arne Vogel Jun 20 '18 at 17:19
-
Why does that regex work? Can someone please post a link that explains this? – Pranav Chaudhary Aug 10 '19 at 05:57
-
`\033[x;yH` will re-position the cursor to row `x`, column `y`. If `x` is 1, it can may be omitted: `\033[;yH`. https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_output_sequences – Dosisod Jun 02 '20 at 23:52
-
3I +1'd you before reading your line about conio.h. Note that, too, is highly non-portable. – Derrick Turk Feb 27 '10 at 17:05
-
I'm not sure about conio.h, but it looks like curses takes care of the GUI in a more comprehensive way than I was initially imagining. I'll have to look into this. Thanks for the suggestion! – devurs Mar 01 '10 at 02:12
For portability, try this:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Then simply call clrscr()
. On Windows, it will use conio.h
's clrscr()
, and on Linux, it will use ANSI escape codes.
If you really want to do it "properly", you can eliminate the middlemen (conio
, printf
, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
#else // !_WIN32
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
#endif
-
1Actually this is really nice. +1 for pointing the "portable" way using ANSI escapes with the horrible but useful clrscr() from conio.h. – Manoel Vilela Aug 29 '17 at 22:55
-
Just for saying: clrscr() is not available on conio.h implementation of mingw compiler – Manoel Vilela Sep 21 '17 at 12:48
A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):
#include <stdlib.h>
void clrscr()
{
system("@cls||clear");
}

- 612
- 7
- 18
-
81- Its monstruous; 2- The OP explicitly asked not to use it; 3- OP is asking for C language command, and `system` calls commands for other languages (said, bash, zsh, batch, etc.). Still +1 to try to make it portable. (I've tested on debian/linux and win7, even inverting the arguments. No need the @ also, because the command will not be on the screen after run) – DrBeco Nov 30 '15 at 04:53
Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}

- 15,395
- 32
- 113
- 196
Since you mention cls
, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:
cls( GetStdHandle( STD_OUTPUT_HANDLE ));

- 40,729
- 5
- 57
- 110
-
1+1 although i didnt ask, but this can be quite useful. And what can be done on unix to 'clear'? – N 1.1 Feb 27 '10 at 16:30
-
@nvl: I only have windows machines at home, and takes about 15 usernames and passwords to log into work machines from here, so I can't test it right now. But I believe ncurses is the route for that (http://linux.die.net/man/3/ncurses). – Mark Wilkins Feb 27 '10 at 17:45
-
I was actually thinking in terms of Unix-based systems - but this helps for Windows. Thanks! – devurs Mar 01 '10 at 02:13
-
I get a "`non-ISO-standard escape sequence, '\e'`" when using this with C11. – Geremia Jan 21 '17 at 20:22
#include <conio.h>
and use
clrscr()

- 1
- 62
- 391
- 407

- 3,794
- 7
- 38
- 48
-
9
-
3And it is not in c standard. Note that , OP mentioned Is there a "proper" way – Muthu Ganapathy Nathan Aug 30 '11 at 16:19
There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.
The entire notion of a "console" is a concept outside of the scope of standard C.
If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.
You can also create an entirely new Console Screen Buffer and make the current one.

- 18,769
- 10
- 104
- 133

- 33,512
- 4
- 61
- 92
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.

- 30,738
- 21
- 105
- 131

- 734
- 5
- 19
-
7
-
\n way immediately poses a next problem: what is min number of newlines has to be written to get **everything** scrolled out of terminal? – Premature Optimization Sep 09 '12 at 23:33
-
2@PrematureOptimization `Forty quadvigiseptanovatriheptasexgesillion`, which we won't have CPUs capable of processing until we have a 2048-bit CPU with a bitchin bignum library. Sorry, you're out of luck. You're just gonna have to live with the fact that people who run their system using the side of the Empire State Building as a projection monitor with a fullscreen terminal running a 1pt font will get an ugly-looking "clear" effect. That's a rare edge case. Otherwise, ~100 lines should do the trick. (Xterm running its default font at fullscreen on a 1080p monitor is only 74 lines tall) – Braden Best Sep 18 '15 at 23:44
-
1@Wilhelm This may not have been what the OP was looking for, but it was EXACTLY what I was looking for. Thanks. – Bryson S. Feb 23 '16 at 00:44
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
-
6`void main` is **very** bad. https://stackoverflow.com/questions/9442121/what-was-wrong-with-void-main – Shravan Oct 05 '14 at 06:48
-
1Its not **very** bad as most compilers will correct it automatically. You are correct that it is wrong and shouldnt be used. – 0-0 Feb 05 '15 at 00:47
-
1`test.c:(.text+0x31): undefined reference to 'clrscr' collect2: error: ld returned 1 exit status`. With stdio.h and stdlib.h included. Not portable. – Braden Best Sep 19 '15 at 01:06
In Windows I have made the mistake of using
system("clear")
but that is actually for Linux
The Windows type is
system("cls")
without #include conio.h
-
How many times do I have to tell everybody?! Don't use `system()`. – Sapphire_Brick Jan 27 '22 at 00:07
The proper way to do it is by using tput
or terminfo
functions to obtain terminal properties and then insert newlines according to the dimensions..

- 131,802
- 30
- 241
- 343
-
4Huh?! Assuming the terminfo call was successful, and the terminal type is a smart (not 'dumb' or 'tty') then you might as well use a terminfo (or termcap) clear screen instruction (clear / cl), rather than pushing multiple newlines, which can be slow on larger X-Window terminals, particularly across networks. – mctylr Feb 28 '10 at 01:06
This should work. Then just call cls(); whenever you want to clear the screen.
(using the method suggested before.)
#include <stdio.h>
void cls()
{
int x;
for ( x = 0; x < 10; x++ )
{
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}

- 410
- 1
- 5
- 14
-
1For this kind of solution, a loop construct (`while` or `for`) would be a little more elegant. See for example: http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1031963460&id=1043284385 – lurker Oct 15 '13 at 12:55
-
2"Yes I could have I guess. But why use a loop when I can copy-paste for the same effect?" Because copy'n'paste violates one of the most important rules in good programming: DRY - Don't repeat yourself – MofX Feb 09 '15 at 18:04
-
1
-
2That prints 160 newlines and leaves the cursor at the bottom of the screen. It's actually possible to have a window taller than 160 lines. – Keith Thompson May 31 '15 at 21:52
-
Seconding Keith Thompson, I get already 159 lines on an old, vertical full HD monitor. The moment I'm upgrading to 4k, there *will* be more than 160 lines... General point: **Never assume "oh, this will suffice in all cases". Cause it won't. Whenever you assume this, you are producing a bug that's just waiting to happen.** Always actually determine your need, or choose methods that always do the right thing. (Same with buffer lengths, string lengths, etc. pp.) – cmaster - reinstate monica Mar 03 '20 at 13:16