Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is data written to a file opened with O_APPEND flag, always written at the end, even with `lseek`?

I have been given a programming assignment:

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?

What I have come up with is:

main() {
    int fd = open("test.txt", O_WRONLY | O_APPEND);
    lseek(fd, 0, SEEK_SET);
    write(fd, "abc", 3);
    close(fd);
}

Upon trying the above, I have found that the data is always written at the end of the file. Why is that? Is it because I have indicated O_APPEND?

like image 875
KarimS Avatar asked Jun 14 '14 19:06

KarimS


1 Answers

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.

like image 91
Adam Rosenfield Avatar answered Oct 14 '22 16:10

Adam Rosenfield