72

Is there a "proper" way to clear the console window in C, besides using system("cls")?

3

14 Answers 14

44
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}.

10
  • 1
    Just 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
  • @anon : This if for UNIX. Do you do the answer for DOS? Mar 22, 2015 at 21:41
  • 1
    How 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.
    – anon
    May 13, 2016 at 1:05
31

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.

2
  • 3
    I +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!
    – devurs
    Mar 1, 2010 at 2:12
27

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
2
  • 1
    Actually 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
19

A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):

#include <stdlib.h>

void clrscr()
{
    system("@cls||clear");
}
1
  • 8
    1- 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, 2015 at 4:53
13

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
  • 1
    _WIN32 will be defined on Windows even if you build for 64-bit.
    – jdt
    Oct 9, 2021 at 14:41
9

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 ));
4
  • 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, 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!
    – devurs
    Mar 1, 2010 at 2:13
  • I get a "non-ISO-standard escape sequence, '\e'" when using this with C11.
    – Geremia
    Jan 21, 2017 at 20:22
9
#include <conio.h>

and use

clrscr()
2
  • 9
    Do note that this is not portable. Feb 27, 2010 at 17:40
  • 3
    And it is not in c standard. Note that , OP mentioned Is there a "proper" way Aug 30, 2011 at 16:19
5

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.

4

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.

4
  • 7
    The OP explicitly said this was NOT what he was looking for. Feb 27, 2010 at 17:40
  • \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.
    – Bryson S.
    Feb 23, 2016 at 0:44
3

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.

3
  • 6
    void main is very bad. stackoverflow.com/questions/9442121/…
    – Shravan
    Oct 5, 2014 at 6:48
  • 1
    Its not very bad as most compilers will correct it automatically. You are correct that it is wrong and shouldnt be used.
    – 0-0
    Feb 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
1

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

1
  • How many times do I have to tell everybody?! Don't use system(). Jan 27, 2022 at 0:07
0

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..

1
  • 4
    Huh?! 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, 2010 at 1:06
-1

There's a other way to clear screen. The clrscr way.

#include <conio.h>
int main() {
  clrscr();
  return 0;
}
-6

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");
    }
}
5
  • 1
    For this kind of solution, a loop construct (while or for) would be a little more elegant. See for example: cprogramming.com/faq/cgi-bin/…
    – lurker
    Oct 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
    – MofX
    Feb 9, 2015 at 18:04
  • 1
    I have done as you suggested, and added a nice loop :)
    – JD3
    Mar 1, 2015 at 22:37
  • 2
    That 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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.