How do you clear the console screen in C?
Is there a "proper" way to clear the console window in C, besides using system("cls")
?
Solution 1:
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}.
Solution 2:
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.
Solution 3:
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
Solution 4:
A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):
#include <stdlib.h>
void clrscr()
{
system("@cls||clear");
}
Solution 5:
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
}