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

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

Leave a Comment