Clearing output of a terminal program Linux C/C++

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("output1\n");
 printf("output2\n");
 rewind(stdout);
 printf("output3\n");
 printf("output4\n");

but this produces

 output1
 output2
 output3
 output4

I was hoping it would produce

 output3
 output4

Does anyone know how to get the latter result?


You can have the desired result both for terminal and pipes if you remember to remove the control characters as well. This is hardcoded for two lines.

#include <stdio.h>

int
main ()
{
    fputs("output1\n",stdout);
    fputs("output2\n",stdout);
    fputs("\033[A\033[2K\033[A\033[2K",stdout);
    rewind(stdout);
    ftruncate(1,0); /* you probably want this as well */
    fputs("output3\n",stdout);
    fputs("output4\n",stdout);
    return 0;
}

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.


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


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 1

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.