Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!nih-csl!lhc!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: problem with fread/fwrite Keywords: fread, fwrite, file pointers Message-ID: <27499@mimsy.umd.edu> Date: 7 Nov 90 04:29:03 GMT References: <402@bally.Bally.COM> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 27 In article <402@bally.Bally.COM> siva@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@cs.umd.edu Path: uunet!mimsy!chris