jeudi 26 février 2015

What does 'transmitted' mean in printf function return?



I'm confused the interpretation of printf's return value and buffered stream in Standard C Library.


In C99:TC3 Standard, 7.19.6.3/p3 defines that printf function returns non-negative "number of characters transmitted" in success. Also, 7.19.3/p3 describes the behaviors of fully/line buffered stream with "transmitted to or from the host environment", and p7 says stdout can be fully buffered stream.


Quote section 7.19.3 with emphasis added:



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.



These definitions lead the following behavior is legal. But it's counterintuitive and unacceptable result (at least for me).



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


What am I wrong in my interpretation? Or it's only one of "implementation-defined" behavior?




Aucun commentaire:

Enregistrer un commentaire