Refresh line in console in C programming

C programming

How can we refresh the current line or lines printed in the console using C programming? Answer in hidden behind VT100 escape codes.

For deleting lines we will need two codes. One for moving cursor one line UP and second for deleting actual line.

cursorup            Move cursor up one line    ^[A
clearline EL2     Clear entire line                    ^[[2K

Example how to use those codes are shown in this small script where are changed two lines.

#include  <stdio.h>

int main ()
{

//write some input	
fputs("output1\n",stdout);
fputs("output2\n",stdout);

//wait one second to change lines above
sleep(1);

//remove both lines
fputs("\033[A\033[2K\033[A\033[2K",stdout);
rewind(stdout);

//write new two lines
fputs("output3\n",stdout);
fputs("output4\n",stdout);

return 0;

}

By using for cycle we can do this counter.

#include <stdio.h>

int main ()
{

int i;

fputs("lets start with counting\n",stdout);

for(i=0;i<10;i++)
{
     	sleep(1);
     	fputs("\033[A\033[2K",stdout);  //erase line
	     printf("output %i\n",i,stdout);	//write new line
     	rewind(stdout);
}

return 0;

}

Leave a Reply