Question

in unistd.h

using open() with the O_APPEND flag gives atomic writes always to the end of the file...

this is great and all, but what if i need to know the offset at which it atomically appended to the file...?

i realize O_APPEND is often used for log files, but I'd actually like to know at what offset in the file it atomically appended.

I don't see any obvious way to do this..? Does anyone know?

Thanks

Was it helpful?

Solution

To get the current position in a file descriptor, use lseek() with offset 0 and whence SEEK_CUR.

int fd = open(...);
if (fd) {
    off_t positionWhereAppendingBegins = lseek(fd, 0, SEEK_CUR);
    write(...);
    close(fd);
}

Note that this will not give you reliable results if the descriptor was opened some other way, i.e. via socket().

OTHER TIPS

The file is written to at the file offset as obtained by the process when the file was opened. If another process writes to the file between the open and the write, then contents of the file are indeterminate.

The correct method of handling multiple process writing to a single file is for all processes to open the file with the O_APPEND flag, obtain an exclusive lock and once the lock is obtained, seek to the end of the file before writing to the file, and finally close the file to release the lock.

If you want to keep the file open between writes, initiate the process by opening the file with the O_APPEND flag. The writing loop in this case is obtain the exclusive lock, seek to the end of the file, write to the file and release the lock.

If you really need the file position, lseek will return the file offset of the callers file descriptor at the time of the call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top