APUE-文件与目录:以O_APPEND标志open的文件,lseek后读写问题

O_APPEND的含义是在每次写之前,都将标志位移动到文件的末端(只有在执行写的时候才移动,移动后不恢复)。表面上读这句话可能会有误解。

提出一个问题:当在O_APPEND打开后,然后用 lseek移动到其他的位置,然后再用write写,这个时候,请问你数据写到哪里去了?

是在末端,还是lseek移动到得位置。答案是在末端。

因为 O_APPEND打开后,是一个原子操作:移动到末端,写数据。这是O_APPEND打开的作用。中间的插入时无效的。例如

[c-sharp]  view plain copy
  1. #include<apue.h>  
  2. #include<unistd.h>  
  3. #include<fcntl.h>  
  4. int main()  
  5. {  
  6.   int fd;  
  7.   char buf[]="@@@@@";  
  8.   
  9.   if((fd=open("test",O_RDWR|O_APPEND)) == -1)  
  10.     {  
  11.       err_sys("open error");  
  12.     }  
  13.   if(lseek(fd,0,SEEK_SET) == -1)  
  14.     {  
  15.       err_sys("lseek error");   
  16.     }  
  17.   if(write(fd,buf,5) != 5)  
  18.     {  
  19.      err_sys("error write");   
  20.     }  
  21.   close(fd);  
  22.   exit(0);  
  23. }  

buf的内容会插入test文件的末尾,之前的lseek是无效的。

 

而对于read,可以读出lseek后的数据,lseek对read有效,如下代码所示:

[c-sharp]  view plain copy
  1. #include<apue.h>  
  2. #include<unistd.h>  
  3. #include<fcntl.h>  
  4. int main()  
  5. {  
  6.   int fd;  
  7.   char buf[]="@@@@@";  
  8.   
  9.   if((fd=open("test",O_RDWR|O_APPEND)) == -1)  
  10.     {  
  11.       err_sys("open error");  
  12.     }  
  13.   if(lseek(fd,0,SEEK_SET) == -1)  
  14.     {  
  15.       err_sys("lseek error");   
  16.     }  
  17.   
  18.   if(read(fd,buf,5) != 5)  
  19.     {  
  20.       err_sys("error read");  
  21.     }  
  22.   printf("%s/n",buf);  
  23.   close(fd);  
  24.   exit(0);  
  25. }  

屏幕会输出test文件开头的几个字符。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值