views:

570

answers:

6

Is there a "proper" way of clearing a screen in C for a console application?
(Besides using:system("cls"))

+2  A: 

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 the library used.

Tom
I +1'd you before reading your line about conio.h. Note that, too, is highly non-portable.
Derrick Turk
I´ve added curses link
Tom
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!
dvrok
A: 

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

Jack
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
+3  A: 

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 ));
Mark Wilkins
+1 although i didnt ask, but this can be quite useful. And what can be done on unix to 'clear'?
N 1.1
@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 (http://linux.die.net/man/3/ncurses).
Mark Wilkins
I was actually thinking in terms of Unix-based systems - but this helps for Windows. Thanks!
dvrok
A: 
#include <conio.h>

and use

clrscr()

Vivek Sharma
Do note that this is not portable.
Billy ONeal
A: 

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.

Wilhelm
The OP explicitly said this was NOT what he was looking for.
Billy ONeal
Ok, reedit done...
Wilhelm
A: 

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 the current one.

John Knoeller