I have a really weird problem with carriage return. I try to rewrite a line multiple times, it works fine if the line has no spaces and doesn't work if it has spaces. For instance this code
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
will type 4 lines "test test" while this code
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
will type a single line "test". What is the problem? I want to be able to rewrite any line disregard if it has spaces or not.
\r
moves the cursor to the beginning of the physical line on the tty. If the previous print wraps the cursor to the next line (ie, the number of spaces + the number of characters in "text text" is larger than the width of the display), then the cursor is on the next physical line. You'll need to use more complex escape sequences to accomplish what you want. (ie, save/restore cursor position.) As an example (this is not portable, but works in many cases), you could do:
fputs( "\0337", stdout ); /* Save the cursor position */
printf( " ... " );
fputs( "\0338", stdout ); /* restore cursor position */
Note that if the cursor is at the bottom of the screen, this will probably not do exactly what you want. The position will be saved at the bottom of the screen, multiple lines of output will scroll, and the cursor will be restored to the bottom of the screen.