How can I erase the current line printed on console in C ? I am working on a linux system
example -
printf("hello"); printf("bye");
I want to print bye on the same line in place of hello.
output bye
How can I erase the current line printed on console in C ? I am working on a linux system
example -
printf("hello"); printf("bye");
I want to print bye on the same line in place of hello.
output bye
You can use a \r
(carriage return) to return the cursor to the beginning of the line:
printf("hello");
printf("\rbye");
This will print bye on the same line. It won't erase the existing characters though, and because bye is shorter than hello, you will end up with byelo. To erase it you can make your new print longer to overwrite the extra characters:
printf("hello");
printf("\rbye ");
Or, first erase it with a few spaces, then print your new string:
printf("hello");
printf("\r ");
printf("\rbye");
That will print hello, then go to the beginning of the line and overwrite it with spaces, then go back to the beginning again and print bye.
Usually when you have a '\r' at the end of the string, only carriage return is printed without any newline. If you have the following:
printf("fooooo\r");
printf("bar");
the output will be:
barooo
One thing I can suggest (maybe a workaround) is to have a NULL terminated fixed size string that is initialized to all space characters, ending in a '\r' (every time before printing), and then use strcpy to copy your string into it (without the newline), so every subsequent print will overwrite the previous string. Something like this:
char str[MAX_LENGTH];
// init str to all spaces, NULL terminated with character as '\r'
strcpy(str, my_string); // copy my_string into str
str[strlen(my_string)] = ' '; // erase null termination char
str[MAX_LENGTH - 1] = '\r';
printf(str);
You can do error checking so that my_string
is always atleast one less in length than str
, but you get the basic idea.
You could delete the line using \b
printf("hello");
int i;
for (i=0; i<80; i++)
{
printf("\b");
}
printf("bye");
When I was a mere lad, we had a library called "curses" that let you draw all over the screen with characters, because we hadn't invented graphics yet.
I think it had to go into full-screen mode first, but that restriction may have since been lifted. Also, it might not be called 'curses' on Linux.
-Wil
You can use VT100 escape codes. Most terminals, including xterm, are VT100 aware. For erasing a line, this is ^[[2K
. In C this gives:
printf("%c[2K", 27);