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

c, linux, terminal

Solution

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;
}

Problem

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?

Original source