problem with fread/fwrite

Chris Torek chris at mimsy.umd.edu
Wed Nov 7 15:29:03 AEST 1990


In article <402 at bally.Bally.COM> siva at bally.Bally.COM (Siva Chelliah) writes:
>When I used fseek before fwrite , it worked.  I do not remember reading 
>anywhere that I should do a fseek before fread/ fwrite.  Is that a bug in the 
>compiler or in my head ?

Put that way, the answer has to be `in your head'. :-)  ANSI standard
X3.159-1989 says that you (the programmer) must call fseek or rewind or
fsetpos before switching from reading to writing or vice versa.  (In
fact, the wording refers to `a successful seek operation', suggesting
that not only must you call fseek or fsetpos or rewind, but also that
if the seek fails, you may not change I/O direction.)

Incidentally:

>char tbuf[7];
>  fread(tbuf,sizeof(tbuf),1,fp);
>  printf("tbuf = %s\n",tbuf);

This is a bug waiting to happen.  (In this test program, of course,
the fread returns 1, having read 7 bytes, of which the last is a '\0'
character, so it is okay here, sort of.)  It is dangerous to print a
`string' that has been read in via fread or read, since neither is
guaranteed to store a '\0' at the end.  (It is also dangerous to ignore
return values, but. . . .)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list