O_APPEND flag and lseek

karim picture karim · Jun 14, 2014 · Viewed 19.3k times · Source

Write a program that opens an existing file for writing with the O_APPEND flag, and then seeks to the beginning of the file before writing some data. Where does the data appear in the file? Why?

this is my code :

main() {
    int fd = open("test.txt", O_WRONLY | O_APPEND);

    lseek(fd, 0, SEEK_SET);
    write(fd, "abc", 3);
    close(fd);
}

and have tried it and found that data has been write in the end of the file, i want to understand why?? because i indicated the O_APPEND flag no that too simple i think

Answer

Adam Rosenfield picture Adam Rosenfield · Jun 14, 2014

When you open a file with O_APPEND, all data gets written to the end, regardless of whatever the current file pointer is from the latest call to lseek(2) or the latest read/write operation. From the open(2) documentation:

O_APPEND
The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2).

If you want to write data the end of the file and then the beginning of it later, open it up without O_APPEND, use fstat(2) to get the file size (st_size member within struct stat), and then seek to that offset to write the end.