ccygwincls

Using 'CLS' command in C causes screen blink


I am trying to clear my console each time I am going to printf something in it (Windows environment with GCC compiler). I am using CygWin and the only way I could manage to do it was with system("cmd /c cls");. That works fine but it causes the screen to blink for a fraction of a second which is obviously annoying.

Is there any alternative way of clearing console screen?


Solution

  • First thing I'd do is stop using cmd to do it. CygWin, assuming you're running somewhere within the shell and not a Windows console, has a "native" option in that you can use either of:

    clear
    tput clear
    

    to clear the screen, without invoking the external cmd interpreter.

    So, from within a program running in CygWin, you can clear the screen with a simple:

    system("clear");
    

    Of course, if you don't want to run any external executables, you can achieve the same end with curses. By way of example, the following program clears the screen for you (make sure you include -lcurses at the end of the compilation command):

    #include <curses.h>
    
    int main (void) {
        WINDOW *w = initscr();
        clear(); refresh(); sleep(2);
        endwin();
        return 0;
    }
    

    Don't get hung up on the fact that it's restored on exit, you wouldn't be using this program as a screen clearing stand-alone thing. Instead, the statements would be incorporated into your own program, between the initscr() and endwin() calls, something like:

    #include <curses.h>
    
    int main (void) {
        char buf[2],
             *msg = "Now is the time for all good men to come to lunch.";
        WINDOW *w = initscr();
    
        buf[1] = '\0';
        clear();
        refresh();
        while (*msg != '\0') {
            buf[0] = *msg++; addstr(buf);
            if ((buf[0] == ' ') || (buf[0] == '.')) {
                refresh();
                sleep(1);
            }
        }
    
        endwin();
        return 0;
    }
    

    This program clears the screen using curses then outputs a message in word-sized chunks.