zoukankan      html  css  js  c++  java
  • 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都不起作用。

  • 相关阅读:
    第六周活动进度表
    第二周活动进度表
    第一周活动进度表
    冲刺二阶段-个人总结10
    冲刺二阶段-个人总结09
    冲刺二阶段-个人总结08
    第一次冲刺-站立会议07
    第一次冲刺-站立会议06
    第一次冲刺-站立会议05
    第一次冲刺-站立会议04
  • 原文地址:https://www.cnblogs.com/wangshuo/p/2033150.html
Copyright © 2011-2022 走看看