• APUE Excercises 3.6 源代码


    3.6  If you open a file for readwrite with the append flag, can you still read from anywhere in the file using lseek? Can you use lseek to replace existing data in the file? Write a program to verify this.

     

    源码:

    #include "apue.h"
    #include <fcntl.h>
    
    int main()
    {
        int fd;
        off_t off;
        char buf[1];
        ssize_t n;
    
        if ( (fd = open("output", O_RDWR|O_APPEND, 0)) == -1)
            err_quit("can't open");
        printf("open file descriptor is: %d\n", fd);
    
        if ( (off = lseek(fd, 2, SEEK_SET)) == -1)
            err_quit("lseek error");
        printf("seek to the file at: %d\n", (int)off);
    
        buf[0] = 'b';
        if ( (n = write(fd, buf, 1)) != 1)
            err_quit("write error");
    
        if ( (off = lseek(fd, 0, SEEK_CUR)) == -1)
            err_quit("lseek error");
        printf("after write, the offset is: %d\n", (int)off);
    
        if ( (off = lseek(fd, 2, SEEK_SET)) == -1)
            err_quit("lseek error");
        printf("seek to the file at: %d\n", (int)off);
    
        if ( (n = read(fd, buf, 1)) == -1)
            err_quit("read error");
        printf("read one character: %c\n", buf[0]);
    
        close(fd);
    
        exit(0);
    }

    output 是我自己的一个文件,只有一行,全是字母a,大小有:

    -rw-r--r-- 1 cat cat 103317545 2011-04-29 22:05 output

    输出结果如下:

    open file descriptor is: 3
    seek to the file at: 2
    after write, the offset is: 103317545
    seek to the file at: 2
    read one character: a

    由此可以看出,当write的时候,file table entry中的 current file offset 又重新变为最后的一个,也就是file status flags 中的 O_APPEND起了作用。

    也可以看出O_APPEND只对write起作用,对于read 和 lseek都不起作用。

  • 相关阅读:
    发呆发呆发呆发呆发呆发呆发
    大众捷达看想吃 v 觉得分开才相聚离开都出现
    yjggj
    test4
    test3
    test2
    test1
    Java并发之线程池ThreadPoolExecutor源码分析学习
    Java并发之AQS同步器学习
    ThreadLocal和ThreadLocalMap源码分析
  • 原文地址:https://www.cnblogs.com/wangshuo/p/2033150.html
Copyright © 2020-2023  润新知