Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!sun-barr!decwrl!ucbvax!hplabs!hpfcso!kah From: kah@hpfcso.HP.COM (Kathy Harris) Newsgroups: comp.sys.hp Subject: Re: fopen/fseek interaction Message-ID: <7370063@hpfcso.HP.COM> Date: 21 Dec 89 22:15:36 GMT References: Organization: Hewlett-Packard, Fort Collins, CO, USA Lines: 50 / hpfcso:comp.sys.hp / arons@sesame.ucdavis.edu (Tom &) / 10:48 am Dec 20, 1989 / >In porting a program from a BSD system to hp-ux version 3.10 on a 9k/800 >I discovered a difference in stdio behavior. > fd = fopen(path, "a") >is used on the BSD system to open, creating if necessary a file. >One, and only one, number is kept in the file by using: > fseek(fd, 0L, 0); > fprintf(fd, "%d\n", n); >to update the file. >On the hp-ux system the fseek's are effectively no-ops, that is >the file consists of as many numbers as there are writes. Changing >the "a" to a "r+" in the fopen works fine if the file exists, but >won't create a new file. "a+" seems to behave the same as "a". >In all cases the fseek returns a 0, indicating success. A workaround >is easy enough to implement, but it is annoying to have to #ifdef the >code. The HP-UX behavior is correct AT&T Sys V.2 stdio behavior. I don't know if BSD defines different behavior or if this is a bug in BSD. The relevant section in the HP-UX manual is from fopen(3S): When a file is opened for append (i.e., when *type* is "a" or "a+"), it is impossible to overwirte information already in the file. Fseek may be used to reposition the pointer to any position in the file, but when output is written to the file, the current file pointer is disregarded. All output is written at the end of the file and causes the file pointer to be respositioned at the end of the output. The ANSI C definition for "append" modes is similar. You have several options to set up code that should be portable: (a) If you always want to start with a "clean" file, use "w+" to do the fopen. (b) If you want to retain an existing file, but create a new one if necessary, then use open(2) to open the file and then fdopen(3S) to set up the stream. Open(2) gives you finer control over how a file is opened. You would want to use the flags O_RDWR and O_CREAT Kathy Harris H.P. Colorado Language Lab