Is there a "proper" way to clear the console window in C, besides using system("cls")
?
-
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 BansalJun 22, 2013 at 16:02
-
1Also here cplusplus.com/articles/4z18T05o– Marcello RomaniJun 27, 2013 at 6:36
-
Nobody has mentioned the standard ASCII control FF (form feed) which ejects a page on printers or printing terminals (such as vt100).– starkNov 8, 2022 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}.
-
1Just to let you know, FWIW, this sequence as is didn't work for me in a windows cmd.exe console. Apr 9, 2013 at 7:56
-
-
1How does it demand POSIX? I don't believe those escape sequences are specified by the POSIX standard. May 31, 2015 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? Sep 18, 2015 at 23:31 -
This code seems to work fine on Windows' CMD, at least in Win10.– anonMay 13, 2016 at 1:05
Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or curses, according to your needs?
Portability is an issue, no matter what library is used.
-
3I +1'd you before reading your line about conio.h. Note that, too, is highly non-portable. Feb 27, 2010 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!– devursMar 1, 2010 at 2: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. Aug 29, 2017 at 22:55
-
Just for saying: clrscr() is not available on conio.h implementation of mingw compiler Sep 21, 2017 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");
}
-
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)– DrBecoNov 30, 2015 at 4: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
}
-
1
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 ));
-
1+1 although i didnt ask, but this can be quite useful. And what can be done on unix to 'clear'?– N 1.1Feb 27, 2010 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 (linux.die.net/man/3/ncurses). Feb 27, 2010 at 17:45
-
I was actually thinking in terms of Unix-based systems - but this helps for Windows. Thanks!– devursMar 1, 2010 at 2:13
-
I get a "
non-ISO-standard escape sequence, '\e'
" when using this with C11.– GeremiaJan 21, 2017 at 20:22
#include <conio.h>
and use
clrscr()
-
9
-
3And it is not in c standard. Note that , OP mentioned Is there a "proper" way Aug 30, 2011 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.
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.
-
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? Sep 9, 2012 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) Sep 18, 2015 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. Feb 23, 2016 at 0: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
-
1Its not very bad as most compilers will correct it automatically. You are correct that it is wrong and shouldnt be used.– 0-0Feb 5, 2015 at 0: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. Sep 19, 2015 at 1: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()
. Jan 27, 2022 at 0: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..
-
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.– mctylrFeb 28, 2010 at 1:06
There's a other way to clear screen. The clrscr way.
#include <conio.h>
int main() {
clrscr();
return 0;
}
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");
}
}
-
1For this kind of solution, a loop construct (
while
orfor
) would be a little more elegant. See for example: cprogramming.com/faq/cgi-bin/…– lurkerOct 15, 2013 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– MofXFeb 9, 2015 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. May 31, 2015 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.) Mar 3, 2020 at 13:16