[comp.lang.c] Two points

bhoughto@hopi.intel.com (Blair P. Houghton) (04/05/91)

In article <15705@smoke.brl.mil> gwyn@smoke.brl.mil (Doug Gwyn) writes:
>In article <3646@inews.intel.com> bhoughto@nevin.intel.com (Blair P. Houghton) writes:
>>	while ( ( c = (char) getchar() ) != (char)EOF )
>
>Assuming that the loop is meant to handle all possible byte values,
>this is also buggy.

I generally use read(2) or fread(3) when I expect binary
input, but no, it has no trouble with ascii(7).

				--Blair
				  "But, Dougiedougiedougiedougie
				   did the _other_ one work, huh,
				   diditdiditdiditdidit huhhhh?"

P.S.  In case you're tired of the bickering, here's a value-added
oldie-but-a-goodie: the file-slurp (with tons of error-checking
and the occasional type-cast omitted, some data inefficiencies,
and maybe even a typo or two... :-).

    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>

    ...
	struct stat stb;
	char *buf;
	FILE *fp;

	stat( "filename", &stb );

	buf = (char *) malloc ( stb.st_size * (sizeof (char *)) );

	fp = fopen( "filename", "r");

	fread( buf, stb.st_size, 1, fp );	/* yippee! */

	fclose(fp);
    ...

The moral of this story is: let fread worry about the blocks and bytes
(although you may want to explore stat(2) to figure out how to deal
with pipes, links, etc., when you can't guarantee an existing file
on the disk).

gwyn@smoke.brl.mil (Doug Gwyn) (04/06/91)

In article <3661@inews.intel.com> bhoughto@hopi.intel.com (Blair P. Houghton) writes:
>In article <15705@smoke.brl.mil> gwyn@smoke.brl.mil (Doug Gwyn) writes:
>>In article <3646@inews.intel.com> bhoughto@nevin.intel.com (Blair P. Houghton) writes:
>>>	while ( ( c = (char) getchar() ) != (char)EOF )
>>Assuming that the loop is meant to handle all possible byte values,
>>this is also buggy.

By the way, the reason I harp on this particular example is because
I have seen a LOT of code fail due to exactly this (and the previous)
construct.  getchar() returns an int; therefore it is that int value
that should be tested against EOF before any possible conversion to a
char (which may or not be signed).  It is easy to get this right..