How do you clear the console screen in C? How do you clear the console screen in C? windows windows

How do you clear the console screen in C?


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 otheralternatives, some of which don't move the cursor to {1,1}.


Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h orcurses, according to your needs?

Portability is an issue, no matter what library is used.


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