gpt4 book ai didi

c - printf函数返回的 'transmitted'是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-04 01:59:50 25 4
gpt4 key购买 nike

我对标准 C 库中 printf 的返回值和缓冲流的解释感到困惑。

C99:TC3 Standard , 7.19.6.3/p3 定义 printf 函数成功返回非负“number of characters transmitted”。此外,7.19.3/p3 描述了完全/行缓冲流的行为,“传输到主机环境或从主机环境传输”,p7 说 stdout 可以是完全缓冲流.

引用第 7.19.3 节并添加强调:

7.19.3 Files

3 When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

7 [...] As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

这些定义导致以下行为是合法的。但这是违反直觉和 Not Acceptable 结果(至少对我而言)。

#include <stdio.h>
#include <assert.h>

// PRECONDITION: `stdout` is fully buffered
int main()
{
int n = printf("abc"); // "abc" is accumulated, and no transmission.
assert(n == 0); // so, return value can be equal to 0 ??
}

我的解释有什么错误?或者它只是“实现定义”行为之一?

最佳答案

printffprintf 的返回值是传输到流的字节数——它是主机环境中的一个对象——而不是最终的目的地。这些字节何时以及如何通过流传输到文件或设备(“从主机环境传输”)是无关紧要的。缓冲不影响流如何从程序中接受字节;只是在将它们发送到关联的文件或设备之前是否以及直到何时保留它们。

关于c - printf函数返回的 'transmitted'是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756793/

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