setbuf重定向 [英] setbuf redirection

查看:70
本文介绍了setbuf重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用setbuf来将stdout重定向到char缓冲区
,但是当我只想将新数据写入stdout时,会产生一些副作用

I use setbuf in order to redirect stdout to char buffer But I get some side effect after it ,when I want to write to the stdout only the new data

如以下代码中所述:

#define bufSize  100
int main()
{
    char buf[bufSize];
    setbuf(stdout, buf);
    printf("123");             //123 is written to the buffer

    setbuf(stdout,NULL);       //123 is written to the stdout(unwanted side effect)
    printf("456");             //123456 appears in the stdout
}

如何解决此问题?

与此有关的其他问题-此代码是否适用于unix / linux / mac os?

Other question regarding this - will this code work for unix/linux/mac os?

有人可以提出解决方案吗?

Can anyone propose the solution for redirection?

推荐答案

我认为您不能重定向 stdout 这样的缓冲区。无论如何,它最终以 stdout 结尾。您只需指定将由流使用的缓冲区。

I don't think you can redirect stdout to a buffer like this. It ends up in stdout anyway. You only specify a buffer which will be used by your stream.

如果使用 setbuf(stdout,NULL) ,它将在后台创建一个新的缓冲区。这将是无缓冲的写操作。即不需要刷新。

If you use setbuf(stdout, NULL), it will create a new buffer behind the scenes. And it will be unbuffered writing.. i.e. no flush needed.

因此,这里没有副作用,只是正常的行为。

So there is no side effect here, just normal behaviour.

如果要重定向 stdout ,请查看此处。前两个答案描述了这样做的两种技术。

If you want to redirect stdout look here. The first two answers describe two techniques doing that.

这篇关于setbuf重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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