return value of fprintf

Kristof Zelechovski giecrilj at
Tue Jan 23 14:47:30 UTC 2007

> -----Original Message-----
> From: Oliver Fromme [mailto:olli at]
> Sent: Tuesday, January 23, 2007 2:40 PM
> To: freebsd-standards at FreeBSD.ORG; giecrilj at
> Subject: Re: return value of fprintf
> K?i?tof ?elechovski <giecrilj at> wrote:
>  > Interestingly enough,
>  > although the stream error indicator is persistent,
>  > it is not taken into account to prevent data corruption as in C++
> streams.
> Can you describe that in more detail, please?  Maybe
> give a code example?  I don't see how data corruption
> could occur if your code is correct.

If you output A, B and C into cout and flushing of B fails, 
you get truncation: only A when you read it back.  
However, if you do the same with fprintf, you get elision: 
you can read back AC and B has been lost.  
This is what I call data corruption.  
It certainly can be prevented, 
and sometimes it can be detected afterwards 
that the file produced contains invalid data, 
only that I did not expect such a difference of behaviour here, 
nor do I understand why the C library prefers 
to let sloppy code leave holes in data.

>  > The reason may be that POSIX streams must set errno on failure
>  > (this is *not* required by the ANSI standard)
>  > but there is no errno value to indicate that the error condition is set
>  > (except EBADF -
>  > but the POSIX standard should be modified to allow this extension,
>  > since at present it only means "Bad file descriptor").
> I'm sorry I don't understand what you mean.  When the
> error indicator is set, errno is always set to an
> appropriate value (e.g. ENOSPC if you run out of space
> on the file system).  If you have an error condition
> on s stream, but you ignore it and continue to perform
> I/O on the stream without removing the cause of the
> problem, you're on your own.  You'll get undefined
> behaviour.

The ANSI standard does not define ENOSPC 
and it does not require the stream I/O functions to set errno.  
Therefore, "always set" is guaranteed to work 
only within the confines of POSIX, otherwise it remains unspecified.

And the behaviour in question is undefined 
in the sense that the standard does not define 
what happens when you a stream for I/O with the error indicator set; 
however, it is not defined as undefined, either.  
The Standard uses the term "undefined behaviour" for errors 
that cannot be easily diagnosed either by the compiler 
or by the runtime library, which is not the case; 
I would rather say it is unspecified and implementation-dependent.


More information about the freebsd-standards mailing list