3

The docs on man lseek say,

If the O_APPEND file status flag is set on the open file description, then a write(2) always moves the file offset to the end of the file, regardless of the use of lseek().

It doesn't say whether or not it moves the file offset to the end, before or after the write(2) call.

Is it possible when a file is open with O_APPEND to lseek to the top and rewrite the file?

2 Answers 2

5

Is it possible when a file is open with O_APPEND to lseek to the top and rewrite the file?

No.

Per the POSIX documentation for write():

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

You can use pwrite(), however:

The pwrite() function shall be equivalent to write(), except that it writes into a given position and does not change the file offset (regardless of whether O_APPEND is set). The first three arguments to pwrite() are the same as write() with the addition of a fourth argument offset for the desired position inside the file. ...

You'd just have to manage the offsets yourself.

Unfortunately, pwrite() is broken on Linux:

POSIX requires that opening a file with the O_APPEND flag should have no effect on the location at which pwrite() writes data. However, on Linux, if a file is opened with O_APPEND, pwrite() appends data to the end of the file, regardless of the value of offset.

So on Linux there's no way to rewrite a file opened with O_APPEND.

0

No, you can't rewrite the file. The file offset is being set to the end before every write is executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.