zoukankan      html  css  js  c++  java
  • 使用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
    ",pos);
    10 wn = write(fd, "-
    ", 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
    ",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被覆盖了,所以不起作用。

  • 相关阅读:
    摄像头置顶成品
    opencv鼠标事件
    opencvinpainting图像修复
    opencvdilate膨胀
    opencverode侵蝕
    opencvOTSU大津法—最大类间方差法
    opencvgetStructuringElement结构元素(内核矩阵)
    opencv时间
    IDEA在代码上无错误提示,但是编译时出现error:非法字符
    计算机端口号
  • 原文地址:https://www.cnblogs.com/thammer/p/4964023.html
Copyright © 2011-2022 走看看