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

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

问题描述

在最现代的炮弹,你可以按下向上和向下箭头,它会说,在提示符下,previous命令是否已执行。我的问题是,如何工作的呢?!

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?

我注意到,像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]\r", &bar[i]);
        fflush(stdout);
        sleep(1);
    }
    printf("\n");
    return 0;
}

这是pretty接近的wget的输出,对不对? \\ r 是一个回车,该终端间$ P $点为移动光标到当前行的开始。

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

您的外壳,如果是庆典,使用 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的,你的外壳等的来源是所有可用的

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

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

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