Note: printing a '\b' is like typing backspace, except the character isn't erased. If you want it to be erased, you can use something like this:
The space writes over whatever character was printed there previously.
Another thing: if you print \r after some text, then something else printed later could overwrite it. In other words, something like this looks strange:
Code:
printf("Hello, World!\r");
printf("Error\n");
In general, I find it's better to print the \r first:
Code:
printf("\rHello, World!");
This method also has the advantage that the cursor appears after the text, as you'd expect, rather than at the beginning of the line.
Also note that neither '\b' nor '\r' can go back a line. Once you print a newline ('\n'), you can no longer edit that line.
Finally, here's my stab at it:
Code:
#include <stdio.h>
#include <time.h>
void twirlybar(void) {
static clock_t last = 0;
static const char *dir = "|/-\\";
static size_t angle = 0;
clock_t now;
now = clock();
if((now - last) / (CLOCKS_PER_SEC / 10.0) >= 0.5) {
if(++angle == sizeof(dir)/sizeof(*dir)) angle = 0;
last = now;
}
putchar('\b');
putchar(dir[angle]);
fflush(stdout);
}
int main(void) {
for(;;) twirlybar();
return 0;
}
(Code highlighted with codeform.) Of course, it would be better to use time_t in a real application, because clock() might be called by something else. And there are far too many static variables in it, passing them in would be a better idea . . . .