[comp.lang.c] Question about feof

garrity@garrity.applicon.UUCP (12/18/86)

   Could someone out there in net-land explain the reason for the 
following behaviour?

   The following routine does exactly what I would expect, that is,
it prints a 0, followed by a 1.

	#include <stdio.h>
	
	main()
	{ FILE	*f;
	  char	string[16];
	  
		f = fopen("/dev/null","r");
		printf("%d\n",fread(string,16,1,f));
		printf("%d\n",feof(f));
	
	}

   If I change the "r" to a "w", then I get a surprise.  The call to
feof() now returns a 0.  Why is that?  I was also a little surprised
to discover that leaving the call to fread() out will also cause feof()
to return 0, but that sort of makes sense.  

BTW, I am running on a Sun with V3.0 of Sun's OS.  
				(i.e. Bsd 4.2 and change :-))

--                                                          -MPG-
-- Mike Garrity
--
-- Things fall apart.  It's scientific.
--
-- snail: Applicon, a division of Schlumberger Systems, Inc.
--        829 Middlesex Tpk.
--        P.O. box 7004
--        Billerica MA, 01821
--
-- uucp: {allegra|decvax|mit-eddie|utzoo}!linus!raybed2!applicon!garrity
--       {amd|bbncca|cbosgd|wjh12|ihnp4|yale}!ima!applicon!garrity

guy%gorodish@Sun.COM (Guy Harris) (12/21/86)

>    Could someone out there in net-land explain the reason for the 
> following behaviour?
> 
>    If I change the "r" to a "w", then I get a surprise.  The call to
> feof() now returns a 0.  Why is that?

Because it never read from "/dev/null", and hence didn't know that it was at
the end of the file.  What did you *expect* it to do?  Unfortunately,
"_filbuf" merely returns EOF if you try to read from something that wasn't
open for reading; it doesn't set the error indication, so "ferror" won't
tell you that you goofed.

jsdy@hadron.UUCP (Joseph S. D. Yao) (12/30/86)

In article <31800001@garrity> garrity@garrity.applicon.UUCP writes:
>   The following routine ... prints a 0, followed by a 1.
>	#include <stdio.h>
>	main()
>	{ FILE	*f; char	string[16];
>		f = fopen("/dev/null","r");
>		printf("%d\n",fread(string,16,1,f));
>		printf("%d\n",feof(f));
>	}
>   If I change the "r" to a "w", ... feof() now returns a 0.

Well, the fread() on a FILE opened for writing should return an
error, and in fact returns(0).  The feof() tests for the EOF bit
in the flags, which is never set in this circumstance -- since
you can write to /dev/null (or, theoretically, any other file)
and never reach bottom.

/* STAMP OUT FASCIST PROGRAMS	*/
/* THAT ENFORCE MINIMUM AMOUNT	*/
/* OF RETURN MATERIAL!		*/
-- 

	Joe Yao		hadron!jsdy@seismo.{CSS.GOV,ARPA,UUCP}
			jsdy@hadron.COM (not yet domainised)