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
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.