如何在 C 中覆盖标准输出 [英] How to overwrite stdout in C

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

问题描述

在大多数现代 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?

推荐答案

它不是在操纵标准输出——而是覆盖终端已经显示的字符.

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]
", &bar[i]);
        fflush(stdout);
        sleep(1);
    }
    printf("
");
    return 0;
}

这与 wget 的输出非常接近,对吧? 是一个回车,终端解释为将光标移回当前行的开头".

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

您的 shell,如果是 bash,则使用 GNU Readline 库,提供更通用的功能,包括检测终端类型、历史管理、可编程键绑定等.

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 中覆盖标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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