How to overwrite stdout in C

后端 未结 8 898
清歌不尽
清歌不尽 2020-12-07 18:13

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?!

相关标签:
8条回答
  • 2020-12-07 18:36

    It's done with the readline library... I'm not sure how it works behind the scenes but I don't think it has anything to do with stdout or streams. I suspect readline uses some sort of cryptic (to me, at least) terminal commands - that is, it cooperates with the terminal program that actually displays your shell session. I don't know that you can get readline-like behavior just by printing output.

    (Think about this: stdout can be redirected to a file, but the up/down-arrow keys trick doesn't work on files.)

    0 讨论(0)
  • 2020-12-07 18:36

    You can use carriage return to simulate this.

    #include <stdio.h>
    
    int main(int argc, char* argv[])
    {
        while(1)
        {
            printf("***********");
            fflush(stdout);
            sleep(1);
            printf("\r");
            printf("...........");
            sleep(1);
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题