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

  • 相关阅读:
    Redis 安装(Windows)
    etcd简介与应用场景
    Nginx+SignalR+Redis(二)windows
    Nginx+SignalR+Redis(一)windows
    Windows 版MongoDB 复制集Replica Set 配置
    走进异步世界async、await
    认识和使用Task
    进程、应用程序域、线程的相互关系
    ASP.NET Core实现类库项目读取配置文件
    用idea做springboot开发,设置thymeleaf时候,新手容易忽略误区
  • 原文地址:https://www.cnblogs.com/wangshuo/p/2033150.html
Copyright © 2011-2022 走看看