O_APPEND的含义是在每次写之前,都将标志位移动到文件的末端(只有在执行写的时候才移动,移动后不恢复)。表面上读这句话可能会有误解。
提出一个问题:当在O_APPEND打开后,然后用 lseek移动到其他的位置,然后再用write写,这个时候,请问你数据写到哪里去了?
是在末端,还是lseek移动到得位置。答案是在末端。
因为 O_APPEND打开后,是一个原子操作:移动到末端,写数据。这是O_APPEND打开的作用。中间的插入时无效的。例如
- #include<apue.h>
- #include<unistd.h>
- #include<fcntl.h>
- int main()
- {
- int fd;
- char buf[]="@@@@@";
- if((fd=open("test",O_RDWR|O_APPEND)) == -1)
- {
- err_sys("open error");
- }
- if(lseek(fd,0,SEEK_SET) == -1)
- {
- err_sys("lseek error");
- }
- if(write(fd,buf,5) != 5)
- {
- err_sys("error write");
- }
- close(fd);
- exit(0);
- }
buf的内容会插入test文件的末尾,之前的lseek是无效的。
而对于read,可以读出lseek后的数据,lseek对read有效,如下代码所示:
- #include<apue.h>
- #include<unistd.h>
- #include<fcntl.h>
- int main()
- {
- int fd;
- char buf[]="@@@@@";
- if((fd=open("test",O_RDWR|O_APPEND)) == -1)
- {
- err_sys("open error");
- }
- if(lseek(fd,0,SEEK_SET) == -1)
- {
- err_sys("lseek error");
- }
- if(read(fd,buf,5) != 5)
- {
- err_sys("error read");
- }
- printf("%s/n",buf);
- close(fd);
- exit(0);
- }
屏幕会输出test文件开头的几个字符。