delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/18/14:39:26

Date: Fri, 18 Jul 1997 14:38:37 -0400 (EDT)
From: "Art S. Kagel" <kagel AT ns1 DOT bloomberg DOT com>
To: "A. Sinan Unur" <asu1 AT cornell DOT edu>
Cc: djgpp AT delorie DOT com
Subject: Re: fread/fwite return value
In-Reply-To: <33CD19F9.4FF2@cornell.edu>
Message-Id: <Pine.D-G.3.91.970718143822.14379G-100000@dg1>
Mime-Version: 1.0

On Wed, 16 Jul 1997, A. Sinan Unur wrote:

> eyal DOT ben-david AT aks DOT com wrote:
> > 
> > On 7/16/97 6:05:33 PM heretic wrote:
> > 
> > >So, I wanted to have error checking and I wrote something like
> > >
> > > if ( fread(blah,blah,blah) == -1 )
> > > {
> > >    oh_no_error ();
> > > }
> > >
> > >But compiler warned that I am comparing unsigned and signed. And it
> > >was right: size_t is unsigned long! Anyone knows how fread or fwrite
> > >can return -1 on error while its return value is unsigned?
> > >
> > cast .  now it is  0xFFFFFFFF.
> > 
> > if (fread (...) == (size_t) -1)
> > {
> >     .....
> > }
> 
> and could you tell me how on earth you would distinguish that from a
> valid number of bytes read by fread???
> 
>   -- Sinan
> 

Actually in:

unsigned long nr;

nr = fread( addr, recsiz, nrecs, FIL );

If nr != nrecs then either there is an end of file condition of an error.
In either case nr record in adr ARE VALID.  Fread NEVER RETURNS -1 unless
2^31 records were actually read (in which case it is not -1 is it?).

The ONLY way to tell if an end-of-file or error condition exists on the   
stream is to call feof(FIL) or FERROR(FIL).  Fread only return zero (0) on
error or EOF if one record is requested and an error or end of file was
detected before that record was completely read!  So the general call
with error detection would be:

  if ((nr = fread( addr, recsiz, nrecs, FIL )) != nrecs)
    if (eof( FIL ))
      fprintf(stderr, "END-OF-FILE reading record.  %d valid recs read.",
          nr );
    else if(ferror(FIL))
      fprintf(stderr, "ERROR reading record.  %d valid recs read.",
          nr );

Art S. Kagel, kagel AT bloomberg DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019