Skip to content
Advertisement

Clearing output of a terminal program in Linux C

I want to clear the output of a C program produced with printf statements. I want to clear only one line, for example:

[source]

printf("AAAAAAAAAAAAAAn");
printf("BBBBBBBBBBBBBBn");
printf("CCCCCCCCCCCCCCn");
printf("DDDDDDDDDDDDDDn");

[terminal]

AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC
DDDDDDDDDDDDDD

[I hope]

AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC

I will “DDDDDDDDDDDDDD” line in write other string. I just want the above A, B, C sentences to left. Only clear D sentences to change the other sentences, unconditionally output D sentences.

How do I do this?

Advertisement

Answer

There’re several ways to delete the DDDDDDDDDDDDDD

  1. Print backspace several times
printf("b");
  1. Print carriage-return and then print something to override the original line
printf("r");
  1. If you are in a newline. You may use terminal commands to move your cursor

such as printf("33[8;5Hhello"); // Move to (8, 5) and output hello

Other commands:

printf("33[XA"); // Move up X lines;
printf("33[XB"); // Move down X lines;
printf("33[XC"); // Move right X column;
printf("33[XD"); // Move left X column;
printf("33[2J"); // Clear screen
...
  1. Don’t forget ncurses

It is the best ways to control the exact layout and format in a terminal

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement