码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-11-14 12:25:50      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:

 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被覆盖了,所以不起作用。

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

标签:

原文地址:http://www.cnblogs.com/thammer/p/4964023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!