I\'m interested in clearing the output of a C program produced with printf statements, multiple lines long.
My initial guess was to use
printf(\"ou
Most terminals support ANSI escape codes. You can use a J (with parameter 2) to clear the screen and an H (with parameters 1,1) to reset the cursor to the top-left:
printf("\033[2J\033[1;1H");
Alternatively, a more portable solution would be to use a library such as ncurses, which abstracts away the terminal-specific details.
You can also try something like this, which clears the entire screen:
printf("\033[2J\033[1;1H");
You can include \033[1;1H
to make sure if \033[2J
does not move the cursor in the upper left corner.
More specifically:
033
is the octal of ESC
2J
is for clearing the entire console/terminal screen (and moves cursor to upper left on DOS ANSI.SYS)1;1H
moves the cursor to row 1 and column 1Once you print something to the terminal you can't easily remove it. You can clear the screen but exactly how to do that depends on the terminal type, and clearing the screen will remove all of the text on the screen not just what you printed.
If you really want fine control over the screen output use a library like ncurses.
One way, is to do a exec('clear').
In fact, when you capture/redirect your stdout (./program > output.file), there is no way how to remove contents of that file, even printf("\033[2J\033[1;1H"); just adds this sequence of characters into it.
As far as C is concerned, stdout is nothing more than a byte stream. That stream could be attached to a CRT (or flat screen), or it could be attached to a hardcopy device like a teletype or even a sheet-fed printer. Calling rewind on the stream won't necessarily be reflected on the output device, because it may not make any sense in context of that device; think about what rewinding would mean on a hardcopy terminal or a sheet-fed printer.
C does not offer any built-in support for display management, so you'll have to use a third-party library like ncurses.