printf函数return中的'transmitted'是什么意思?

What does 'transmitted' mean in printf function return?

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

C99:TC3 Standard中,7.19.6.3/p3定义printf函数return的非负"number of characters transmitted"成功。 此外,7.19.3/p3 描述了 fully/line 缓冲流的行为,“ 传输 到主机环境或从主机环境传输”,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.

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

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

我的解释哪里错了? 或者这只是 "implementation-defined" 行为之一?

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

单词“transmitted”表示字节穿过某个接口。我提交7.19.6.3指的接口是printf和设备驱动之间的接口,而7.19.3指的接口是设备驱动的输出。

此外,我认为您提出的解释会使 printf 中的 return 值变得任意且反复无常。

因此,我得出结论,您的示例代码中的 printf 将始终 return 3.