使用O_APPEND标志打开文件对文件进行lseek后进行读写的问题

 1 fd = open("./newfile", O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
 2 if ( fd < 0 )
 3 {
 4        perror("open");
 5        return -1;
 6 }
 7 pos = lseek(fd, 2, SEEK_CUR);
 8 
 9 printf("pos:%d\n",pos);
10 wn = write(fd, "-\n", 2);
11 if  ( wn < 0 )
12 {
13        perror("write");        
14        close(fd);
15        return -1;
16 }
17 
18 close(fd);
19 return 0;

以上是lseek后的写操作,newfile内容是26个字母,执行得到的结果是:

thomas@thomas-laptop:~/test/apu$ ./a
pos:2
thomas@thomas-laptop:~/test/apu$ cat newfile
abcdefghijklmnopqrstuvwxyz
-
thomas@thomas-laptop:~/test/apu$

而进行读操作:

 1     fd = open("./newfile", O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
 2     if ( fd < 0 )
 3     {
 4         perror("open");
 5         return -1;
 6     }
 7     pos = lseek(fd, 2, SEEK_CUR);
 8 
 9     rn = read(fd, buf, 3);
10     if ( rn < 0 )
11     {
12         perror("read");
13         close(fd);
14         return -1;
15     }
16     printf("buf:%s\n",buf);

thomas@thomas-laptop:~/test/apu$ ./a
buf:cde

这次lseek起到了作用,这是来自APUE第三章一个练习题,仔细看看O_APPEND的定义就知道了,man 一下

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

结合一下其他资料,O_APPEND只是在write时原子性的把操作位置定位到末尾,程序中相当于前面那个lseek被覆盖了,所以不起作用。

转载于:https://www.cnblogs.com/thammer/p/4964023.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值