Scott Scott - 3 months ago 30
C Question

How to overwrite stdout in C

In most modern shells, you can hit the up and down arrows and it will put, at the prompt, previous commands that you have executed. My question is, how does this work?!

It seems to me that the shell is somehow manipulating stdout to overwrite what it has already written?

I notice that programs like wget do this as well. Does anybody have any idea how they do it?


It's not manipulating stdout -- it's overwriting the characters which have already been displayed by the terminal.

Try this:

#include <stdio.h>
#include <unistd.h>
static char bar[] = "======================================="
int main() {
    int i;
    for (i = 77; i >= 0; i--) {
        printf("[%s]\r", &bar[i]);
    return 0;

That's pretty close to wget's output, right? \r is a carriage-return, which the terminal interprets as "move the cursor back to the start of the current line".

Your shell, if it's bash, uses the GNU Readline library, which provides much more general functionality, including detecting terminal types, history management, programmable key bindings, etc.

One more thing -- when in doubt, the source for your wget, your shell, etc. are all available.