Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!mnetor!uunet!husc6!cmcl2!brl-adm!brl-smoke!gwyn
From: gwyn@brl-smoke.ARPA (Doug Gwyn )
Newsgroups: comp.lang.c
Subject: Re: stdio error detection
Message-ID: <6748@brl-smoke.ARPA>
Date: Thu, 26-Nov-87 22:47:55 EST
Article-I.D.: brl-smok.6748
Posted: Thu Nov 26 22:47:55 1987
Date-Received: Sun, 29-Nov-87 18:38:58 EST
References: <289@cresswell.quintus.UUCP>
Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) )
Organization: Ballistic Research Lab (BRL), APG, MD.
Lines: 48
Keywords: errno fclose fopen stdio errors

In article <289@cresswell.quintus.UUCP> ok@quintus.UUCP (Richard A. O'Keefe) writes:
>- Under what conditions (other than not-open file or invalid address &c)
>  can this return an error result?

Assuming no bugs in your code, fclose() can fail only if the stream had some
unwritten buffered data and an I/O error occurred while writing it out.

>- How can I tell what went wrong?

Clear errno before invoking fclose(), then if it fails, examine errno.

>- What, if anything, can I *do* about it?

Probably not much.  A disk filled up or went off-line or something like that.

>Another thing is fopen().  How can I find out whether a NULL result means
>...

Again, the simplest thing is to let errno tell you.

>which is so painful that I usually don't do it, and just say
>	: cannot (read|write|append) 

That is the traditional way to report the failure.  Finer discrimination
between causes of stdio errors is, as you remark, a pain.  There is also
no standardization for low-level error causes outside the UNIX environment,
so a fully portable approach to reporting details of errors is impossible

>	if (--stdio function fails--) { perror(--suitable argument--); ...
>This doesn't seem like a good idea.

True in general, but if you assume that the stdio function failed because
some system call failed, it is fairly reliable.

>It would be really nice if
>the stdio functions were defined to set errno (any ANSI C people care to
>comment?).

Set errno to what?  There is no way the C standards committee is going to
attempt to identify all OS-dependent low-level error causes and provide
standard encodings for all of them!

> Of course there is no official errno code which means that
>"malloc() ran out" -- another nasty gap.

In a UNIX environment, ENOMEM (or, less likely, EAGAIN) are the errno
codes for inability to obtain more memory for the process.  If malloc()
cannot obtain enough memory, one of these codes will be set in errno.