gpt4 book ai didi

c - setbuf重定向

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:37 26 4
gpt4 key购买 nike

我使用 setbuf 将标准输出重定向到字符缓冲区但是当我只想将新数据写入标准输出时,我得到了一些副作用

如以下代码所示:

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

谁能提出重定向的解决方案?

最佳答案

setbuf() 函数不会将输出重定向到缓冲区。它只是告诉标准 I/O 库“使用这个缓冲区;不要自己分配”。

您还应该在每个打开的流中使用一次 setbuf()(在它打开之后立即并且在对它进行任何其他操作之前)并且之后不要管它。如果你多次使用它,你会进入未定义的行为 - 你看到的是可以接受的,因为所需的行为是未定义的。

C99 标准说:

§7.19.5.5 The setbuf function

Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer), with the value _IONBF for mode.

§7.19.5.6 The setvbuf function

The setvbuf function may be used only after the stream pointed to by stream has been associated with an open file and before any other operation (other than an unsuccessful call to setvbuf) is performed on the stream.

关于c - setbuf重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7085257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com