博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

APUE Excercises 3.6 源代码

Posted on 2011-04-29 22:13  天地玄黄  阅读(359)  评论(0编辑  收藏  举报

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都不起作用。