Search code examples
cescaping

How to take to cursor to the end of the line (Without disturbing the content of the line) after we use the escape sequence \r in C?


I want to know that how we can take the cursor to the end of the line without over writing the contents of the line:

For example:

#include <stdio.h>

int main(void)
{
    printf("This is a test line\r");
    printf("###"); // Cursor moves to start of the line and over writes the content
    printf("I want to print this at the end of the line"); // I want to take the cursor to the end of the line and then print this
    return 0;
}

Output:

###I want to print this at the end of the line

But I want the output to be like this (by cursor movement, not by simply using this in printf()):

###s is a test lineI want to print this at the end of the line

What's the method to do this in C?


Solution

  • Using ANSI escape sequences works for me

    #include <stdio.h>
    
    int main(void) {
        printf("One Two Three\x1b[s\r");
        //                   ^^^^^^      ESC[s ==> save cursor position
        printf("###\x1b[u");
        //         ^^^^^^                ESC[u ==> restore cursor position
        printf("FOUR FIVE SIX\n");
    }
    

    Apparent output

    ### Two ThreeFOUR FIVE SIX