How do I clear the screen in C?

45,498

Solution 1

The best way to clear the screen is to call the shell via system(const char *command) in stdlib.h:

system("clear"); //*nix

or

system("cls"); //windows

Then again, it's always a good idea to minimize your reliance on functions that call the system/environment, as they can cause all kinds of undefined behavior.

Solution 2

You need to check out curses.h. It is a terminal (cursor) handling library, which makes all supported text screens behave in a similar manner.

There are three released versions, the third (ncurses) is the one you want, as it is the newest, and is ported to the most platforms. The official website is here, and there are a few good tutorials.

#include <curses.h>

int  main(void)
{
     initscr();
     clear();
     refresh();
     endwin();
}

Solution 3

Windows:

system("cls"); // missing 's' has been replaced

Unix:

system("clear");

You can wrap this in a single, more portable piece of code like so:

void clearscr(void)
{
#ifdef _WIN32
    system("cls");
#elif defined(unix) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
    system("clear");
//add some other OSes here if needed
#else
    #error "OS not supported."
    //you can also throw an exception indicating the function can't be used
#endif
}

Note the check for unix is pretty expansive. This should also detect OS X, which is what you're using.

Solution 4

The availability of this function or similar ones like clrscn() are very system dependent and not portable.

You could keep it really simple and roll you own:

#include <stdio.h>

    void clearscr ( void )
    {
      for ( int i = 0; i < 50; i++ ) // 50 is arbitrary
        printf("\n");
    }
Share:
45,498
user2651382
Author by

user2651382

Updated on October 15, 2020

Comments

  • user2651382
    user2651382 over 3 years

    I want to clear all the text that is on the screen. I have tried using:

    #include <stdlib.h>
    sys(clr);
    

    Thanks in advance! I'm using OS X 10.6.8. Sorry for the confusion!

    • JSQuareD
      JSQuareD almost 11 years
      What OS are you using?
    • Tarik
      Tarik almost 11 years
      Duplicate question. Please check.
    • Paul Renton
      Paul Renton almost 11 years
      I believe this question's answer will depend on the OS you are using. You need to edit the question and tell us which OS you are using
    • Mike D
      Mike D almost 11 years
    • Crowman
      Crowman almost 11 years
      Please consider the wisdom of doing this, when you find an answer. Many users, me included, don't appreciate programs randomly clearing their screens, or going off and doing something when I've pressed a key but before I've been given the opportunity to confirm it's the input I wanted to give by pressing Enter. Unless you're using an actual TUI, this kind of thing is never necessary, and usually just annoying.
    • Sid
      Sid almost 11 years
      So this function clrscr(); of the conio.h library wont work in C? I used it so many times.
    • Commander Worf
      Commander Worf almost 11 years
      @Sid: clrscr() isn't in stdio.h, it's in conio.h, which isn't POSIX compliant or available on most (edit) compilers.
    • Crowman
      Crowman almost 11 years
      @Sid: clrscr() may be in your stdio.h header (stdio.h is not a "library"), but it's not in C's.
    • Sid
      Sid almost 11 years
      Thanks for clarification!
  • tallen
    tallen almost 11 years
    Why would you down vote this, curses is a way to do this
  • brianmearns
    brianmearns almost 11 years
    That's not C, it's C++. And that doesn't clear the screen, just fills it with blank lines. Two key differences being that the cursor ends up at the bottom of 50 empty lines (instead of at (0,0)) and that the scrollable buffer is not erased as it would be if you cleared the screen.
  • brianmearns
    brianmearns almost 11 years
    Not sure who downvoted it, but curses is a way to do it, not the way.
  • Sam I am says Reinstate Monica
    Sam I am says Reinstate Monica almost 11 years
    This might qualify as a comment, but it most definitely is not an answer, and is unlikely to help the OP. Maybe if you wrote what curses.h was and/or why he would check out curses.h it would be better
  • David Elliman
    David Elliman almost 11 years
    It compiles as C for me. It works. Most command line programs do not use cursor addressing.
  • tallen
    tallen almost 11 years
    as such it is an answer
  • Sam I am says Reinstate Monica
    Sam I am says Reinstate Monica almost 11 years
    @tallen as is is as not an answer. It may be a hint, but the button doesn't say "post your hint" it says "post your answer"
  • JSQuareD
    JSQuareD almost 11 years
    I downvoted because: 1) You didn't explain what curses.h is and didn't even give a link. 2) you didn't give a code example. 3) curses.h is not a standard library, and I think it's even a Unix-specific example, making this solution even less portable than the standard solution. 4) including an entire (non-standard) library just for clearing the screen might be a bit of an overkill.
  • Jiminion
    Jiminion almost 11 years
    More information added.
  • tallen
    tallen almost 11 years
    this is the way you did it before the VT terminal!
  • Edwin Buck
    Edwin Buck almost 11 years
    What a waste, you don't fork a full process for do this, and why introduce the race condition?
  • Jiminion
    Jiminion almost 11 years
    +1 to Edwin for bringing up the process issue.
  • wildplasser
    wildplasser almost 11 years
    This is in fact the only truly portable solution. (but it could cost a lot of paper on your TTY ;-)
  • Commander Worf
    Commander Worf almost 11 years
    How would you do it? Including the ncurses library is a bit overkill IMO, and one 'clear' process will hardly slow down most programs.
  • Jiminion
    Jiminion almost 11 years
    Uses system call => extra process. Hmm.....
  • Edwin Buck
    Edwin Buck almost 11 years
    If you think adding a library is overkill, try running a program. It adds all the libraries used to develop the program. Also, since, that program is a shell it then interprets the arguments, does a look-up for the program on the path, and then launches another program. All of that for a screen clear? ncurses is a far better choice, and if someone slips in a rogue copy of "clear" or "cls", or has the ability to reorder their path, you didn't just introduce a security hole.
  • gravitas
    gravitas almost 11 years
    Can someone explain to me the race-condition this introduces and how forking would prevent it?
  • Edwin Buck
    Edwin Buck almost 11 years
    You avoid it by not running two programs to do one job. If you decided to go with this solution, then you avoid it by polling the operating system to ensure that the clear program has exited cleanly before writing any further text to the screen (which would require a write-lock in your program). This "simple" solution is very problematic, to the point it's not simple to fix. Use the solution (documented by Jim) that costs you an extra five lines of code, but isn't subject to this race condition, because all of your screen logic is in one process.
  • JSQuareD
    JSQuareD almost 11 years
    @Jim Good point, but it is the most no-nonsense way to do this. And in a simple console-application making a system-call every now and then will hardly be an issue for performance.
  • Jiminion
    Jiminion almost 11 years
    Yes. I can see how both solutions have their place.
  • Edwin Buck
    Edwin Buck almost 11 years
    I added a bit more info, for those who can't be bothered to google.
  • Jiminion
    Jiminion almost 11 years
    @EdwinBuck Thank you. I guess ncurses is the best choice at this point.
  • JSQuareD
    JSQuareD almost 11 years
    @edwinbuck exactly what makes this unportable? Also, whatever OS you're using, stdlib.h is the only header that needs to be included, so no preprocessor logic is required there.
  • Edwin Buck
    Edwin Buck almost 11 years
    @JSQuareD You are right about the header includes. My apologies. The part that I meant to express in my complaints is that it assumes a very particular environment configuration, which while stock, is easily modified way past deployment. In that sense, it isn't functionally assured unless you can control the execution environment, over the entire life of the program. Not worth the hassle in my opinion, but you are right, the source code is portable.
  • JSQuareD
    JSQuareD almost 11 years
    @edwinbuck hmm.. I guess. But I find it hard to believe that people would undefine these macros or modify the meaning of cls or clear. And if they did, it's hardly the source code that's to blame. On any rate, I'm not saying curses isn't a more portable/elegant solution, I just think it's a bit of an overkill if you just want to clear the screen. Plus, it might be a fair bit of work to implement into an existing console application.
  • brianmearns
    brianmearns almost 11 years
    @DavidElliman: It compiles as C because you changed it =J. cout << like you originally had is not C as you cannot do operator overloading in C. My point about it not actually clearing the screen was that your cursor is left at the bottom of the console instead of the top. It's not just a matter of cursor addressing, it's a very definite cosmetic difference. When you clear the screen and start typing, you expect it to appear on the first line, not the last. It may be functionally the same in most cases, but it looks and feels very different to the user.
  • Admin
    Admin almost 5 years
    system("cls || clear");