Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!tut.cis.ohio-state.edu!ucbvax!hplabs!hpda!hpcupt1!hpisod2!decot From: decot@hpisod2.HP.COM (Dave Decot) Newsgroups: comp.sys.hp Subject: Re: fopen/fseek interaction Message-ID: <16710040@hpisod2.HP.COM> Date: 21 Dec 89 07:56:40 GMT References: Organization: Hewlett Packard, Cupertino Lines: 56 > 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. Since this code is opening the file for append (which means all writes should be done at the end) and seeking to the beginning, and not using the more intuitive "w+" flag to accomplish what appears at first glance to be the same effect, I would assume that the code is written this way as some kind of attempt to update the file atomically without conflicting with some other application. It is unclear that it would succeed at that goal even on the BSD system. > 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. Indeed it should. The "a" asks for "append mode". According to open(2) on both systems, that means every write appends to the end of the file, regardless of the current file offset. > 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. Perhaps just use "w+" mode, or if this is an attempt to keep a sequence number from being updated simultaneously by different processes, rewrite the code to do proper file locking. > I am not sure whether the difference is a bug in either the BSD or > hp-ux system, or some BSD/System V semantic difference. Does anyone > know? The man page explanations for fopen on both systems are > virtually identical. The difference is the two interpretations of the word "append" for fopen(). See O_APPEND on open(2) for the (consistent) definitions of how appending to files is done. HP-UX sets the O_APPEND flag to do fopen()'s "a" append mode, BSD does not set O_APPEND, so writes do not always occur at the end of the file. Dave Decot HP DISCLAIMER: This article is not necessarily the opinion of Hewlett-Packard Company. It is provided without warranty of any kind, and the effects of its use is solely the responsibility of the user.