Issue
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
?
Solution
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 eachwrite(2)
, the file offset is positioned at the end of the file, as if withlseek(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.
Answered By - Adam Rosenfield Answer Checked By - Katrina (WPSolving Volunteer)