如何在C中覆盖stdout [英] How to overwrite stdout in C

查看:225
本文介绍了如何在C中覆盖stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数现代shell中,您可以点击向上和向下箭头,它会在提示符下放置您执行的以前的命令。我的问题是,这是如何工作的?

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

在我看来,shell是以某种方式操纵stdout覆盖已经写的东西。

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

我注意到像wget这样的程序也做到了。是否有人知道它们是如何做的?

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

推荐答案

这不是操作stdout-它覆盖已经显示的字符

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

请尝试以下操作:

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

非常接近 wget 的输出,对不对? \r 是回车,终端解释为将光标移回当前行的开头。

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".

你的shell,如果它 bash ,使用 GNU Readline library ,它提供了更加通用的功能,包括检测终端类型,历史记录管理,可编程键绑定等。

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.

更多的东西 - 当有疑问,你的wget,你的shell等的源都可用。

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

这篇关于如何在C中覆盖stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆