Email List: Xaustin-group-lX
[All Lists]

Re: return value of lseek(fd, 0, SEEK_CUR) for O_APPEND files

To: Martin Sebor <msebor@xxxxxxxxx>
Subject: Re: return value of lseek(fd, 0, SEEK_CUR) for O_APPEND files
From: Eric Blake <ebb9@xxxxxxx>
Date: Tue, 12 May 2009 18:47:35 -0600
Cc: austin-group-l@xxxxxxxxxxxxx
References: <4A0A0394.9070003@gmail.com>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

According to Martin Sebor on 5/12/2009 5:17 PM:
> On the two implementations I've tried lseek(fd, 0, SEEK_CUR) returns
> 0 for files opened with the O_APPEND bit set.

As far as I can tell, the standard requires open(O_APPEND) to position the
file offset (lseek) at the beginning until after a write to the fd:

"The file offset used to mark the current position within the file shall
be set to the beginning of the file."
http://www.opengroup.org/onlinepubs/9699919799/functions/open.html

But fopen("a") is allowed to set the stream position (ftell) at the
beginning (as on Linux) or at the end (as on BSD) until after the first
action that forces the stream to write to the underlying fd, and there is
no explicit statement stating that the actions of fopen() reposition the
underlying fd away from its original position of 0.  After all, the stream
position can be independent of the fd position, if you haven't used fflush
to synchronize the two.

>     fp = fopen (__FILE__, "a");
>     fd = open (__FILE__, O_WRONLY | O_APPEND);
> 
> #define PRINT(A)   printf ("%s = %li\n", #A, (A))
> 
>     PRINT (lseek (fileno (fp), 0, SEEK_CUR));
>     PRINT (ftell (fp));

Indeterminate.  The standard is silent, both behaviors are permitted.  In
fact, this is the very bug that bit me when I released GNU M4 1.4.10,
which worked on Linux but failed under BSD.

>     PRINT (lseek (fd, 0, SEEK_CUR));

Must print 0.

- --
Don't work too hard, make some time for fun as well!

Eric Blake             ebb9@byu.net
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkoKGKcACgkQ84KuGfSFAYBRfQCeOdiFY6jq+EiRRnP5g0ysG6HB
49EAoIxAhGz745kp1DOjRNSgwCTDM2vl
=6Cuh
-----END PGP SIGNATURE-----

<Prev in Thread] Current Thread [Next in Thread>