zoukankan      html  css  js  c++  java
  • 有关O_APPEND标志和lseek()的使用

    编程之路刚刚开始,错误难免,希望大家能够指出。

    O_APPEND表示以每次写操作都写入文件的末尾。
    lseek()可以调整文件读写位置。

    <<Linux/UNIX系统编程手册>>上有这样一个问题:当在O_APPEND打开后,然后用 lseek移动文件开头,然后再用write写,这个时候,数据会显示在文件中的哪个位置?为什么?

    先上代码:

     1 #include <unistd.h>
     2 #include <string.h>
     3 #include <fcntl.h>
     4 #include <stdio.h>
     5 
     6 int main(void)
     7 {
     8     int fd = open("test_open.txt",O_RDWR | O_APPEND);
     9     if(fd < 0)
    10     {
    11         perror("open");
    12     }
    13 
    14     int pos = lseek(fd,0,SEEK_SET);
    15     if(pos != 0)
    16     {
    17         printf("lseek error
    ");
    18         return -1;
    19     }
    20 
    21     int size =write(fd,"world",strlen("world"));
    22     if(size != 5)
    23     {
    24         printf("write error
    ");
    25     }
    26 
    27     close(fd);
    28     return 0;
    29 }

    test_open.txt的内容随意,编译运行程序会发现数据显示在了文件最后,这个原因在APUE的3.8章节提到了:
      对于普通文件,写操作从文件的当前偏移量处开始。如果在打开该文件时,指定了O_APPEND选项,则在每次写操作之前,将文件偏移量设置在文件的当前结尾处。在一次成功写入之后,该文件偏移量增加实际写的字节数。

      其实就是在说O_APPEND会将lseek()的作用抵消掉。

  • 相关阅读:
    散列函数之单散列算法
    NET 使用 RabbitMQ
    leetCode
    Swift 1
    C#并发集合
    多进程与多线程1
    开发编译器
    APUE1
    微服务架构
    ExceptionHandlerMiddleware中间件如何呈现“定制化错误页面”
  • 原文地址:https://www.cnblogs.com/jiangyibo/p/8697159.html
Copyright © 2011-2022 走看看