From: Erik Max Francis Newsgroups: comp.os.msdos.djgpp Subject: Re: fread/fwite return value Date: Thu, 17 Jul 1997 08:30:34 -0700 Organization: Alcyone Systems Lines: 45 Message-ID: <33CE3A9A.295543E2@alcyone.com> References: <199707161302 DOT PAA20053 AT free DOT polbox DOT pl> NNTP-Posting-Host: newton.alcyone.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk heretic AT polbox DOT com wrote: > I've noticed a kind of anomaly while writing a program using > fwrite/fread functions. First take a look at library reference: > > size_t fread(void *_ptr, size_t _size, size_t _nelem, FILE *_stream); > > (...) > > Return value > ============ > The number of items of size SIZE read, or -1 on error. The library reference is wrong, and fread's return type being unsigned is consistent with its return type. From ANSI C, 7.9.8.1: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); The fread function returns the number of elements successfully read, which may be less than `nmemb' if a read error or end-of-file is encountered. That is, it always returns the number of elements (not number of bytes!) successfully read; an error indication would not be a negative number, but rather less than the number of elements you asked it to read. fwrite is analogous with respect to this behavior. That is, Block *data; int elements; /* ... */ if (fread(block, sizeof(Data), elements, file) != elements) /* error condition ... */ -- Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com Alcyone Systems / web / http://www.alcyone.com/max/ San Jose, California, United States / icbm / 37 20 07 N 121 53 38 W \ "All the gods are dead / except the god of war." / Eldridge Cleaver