| Victor 2004-01-23, 4:56 pm |
| I noticed that when I opened a file using open( ) with the O_APPEND
flag that I have to
first write to the file in order to have lseek( ) return the offset
value equivalent to the offset
from the beginning of the file. For example, the code below
fd = open( my_file, O_APPEND | O_WRONLY );
printf( "Current offset following lseek( fd, O, SEEK_CUR): %d\n",
( int ) lseek( fd, 0, SEEK_CUR ) );
will print the text
Current offset following lseek( fd, O, SEEK_CUR): 0
If I write to the file and then call lseek( fd, 0, SEEK_CUR ), I will
get the actual offset from
the beginning of the file
fd = open( my_file, O_APPEND | O_WRONLY );
printf( "Current offset following lseek( fd, O, SEEK_CUR): %d\n",
( int ) lseek( fd, 0, SEEK_CUR ) );
bytes_written = write( fd, buffer, num_bytes );
init_off = lseek( fd, 0, SEEK_CUR ) - (off_t ) bytes_written;
printf( "Actual initial offset to end of file: %d\n", init_off );
printf( "Current file offset: %d\n", ( int ) lseek( fd, 0,
SEEK_CUR ) );
will give me output
Current offset following lseek( fd, 0, SEEK_CUR): 0
Actual initial offset to end of file: 12
Current file offset: 23
Note that this suggests that the initial file size was 12 bytes, and
11 bytes were written to
fd.
In summary, lseek( fd, 0, SEEK_CUR ) will return (off_t ) 0 after a
file is opened for
appending. Once at least one byte is written to fd, lseek( fd, 0,
SEEK_CUR ) will
return the offset from the beginning of the file. Is there a better
way to get the offset to
the end of the file? I could have opened the file without the
O_APPEND flag, and called
lseek( fd, 0, SEEK_END ), but this not safe if multiple processes are
appending to the same
file. By the way, forgive my lack of error checking above; I have
omitted it for the sake of
clarity in this post, not in the code itself.
Thanks for your help,
Victor
|