cwindowsconsole-application

basic console animation in c


I want to know how to "animate" something in the windows console with c.

I am unsure of wich prompts/keywords i have to google to find the answers i want.

This is just a project for me to get to know c and the console so efficiency and optimization is not really a concern for me yet. I usually work with high-level languages and mostly with oop.

I just used printf() in nested loops for now, to draw "frames".

What i want is to "replace" the printed lines with new ones, instead of printing my "frames" below each other.


Solution

  • If you just want to redraw the last line, you can use \r to move cursor to the beginning of the current line:

    const char lines[] = { '|', '/', '-', '\\' };
    for (size_t i = 0; i < 100; i++) {
        printf("\rin progress: %zu %c", i, lines[i % 4];
        sleep(1);  // replace with proper syscall
    }
    

    Just remember to add a bunch of spaces at the end if the new line is shorter than previous one, to draw over any leftovers. This may not work correctly if the line is so long that it wraps.

    For more complicated animations you can use ANSI escape codes (any modern terminal should support it) to move the cursor around, this is what most TUI programs like Vim use under the hood.