美文网首页深入理解计算机系统
追加标志打开一个文件,能否仍用lseek在任一位置开始读?能否用

追加标志打开一个文件,能否仍用lseek在任一位置开始读?能否用

作者: MachinePlay | 来源:发表于2020-01-21 19:31 被阅读0次

    如果使用追加标志打开一个文件以便读、写,能否仍用lseek在 任一位置开始读?能否用lseek更新文件中任一部分的数据?请编写一段 程序验证。

    猜测

    可以

    验证代码

    #include <iostream>
    #include <unistd.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <string.h>
    #define BUFFSIZE 4096
    int main(int argc, char * argv[]) {
        std::cin.sync_with_stdio(false);
        std::cin.tie(NULL);
        printf("test append and lseek\n");
    
        try{
            int fd = open(argv[1], O_RDWR | O_CREAT |  O_APPEND);
            if (!fd) {
                std::cout << "open file failed" << std::endl;
            }
            int len = 0;
            char buf[BUFFSIZE];
            memset(buf, 0, BUFFSIZE);
            len = read(fd, buf, BUFFSIZE);
            printf("read %d bytesn\n", len);
            close(fd);
    
            //write
            fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND);
            if(!fd) {
                std::cout << "open file failed" << std::endl;
            }
            char name[] = "oooooooooo";
            len = write(fd, name, strlen(name));
            if(!len) {
                std::cout << "write error" << std::endl;
            }
            std::cout << "length of write " << len << std::endl;
            lseek(fd, 0, SEEK_SET);
            len = read(fd, buf, 5);
            printf("after lseek read content %s\n", buf);
    
            lseek(fd, 0, SEEK_SET);
            len = write(fd, name, strlen(name));
            if(!len) {
                std::cout << "write failed after failed\n" << std::endl;
            }
            printf("write %s after lseek\n", buf);
        }
        catch (std::exception &e)
        {
            std::cout << e.what() << std::endl;
        } catch (...) {
            std::cout << "unknown error" << std::endl;
        }
    
        return 0;
    }
    

    hello.txt文件内容

    wodanimade
    
    image.png

    测试后文件内容

    wodanimadeoooooooooooooooooooo
    

    也就是不能覆盖写

    结论

    如果使用追加标志O_APPEND打开一个文件以便读、写; 能用lseek在任一位置开始读,不能用lseek更新文件中任一部分的数据,只能从文件末尾更新数据。

    相关文章

      网友评论

        本文标题:追加标志打开一个文件,能否仍用lseek在任一位置开始读?能否用

        本文链接:https://www.haomeiwen.com/subject/anbezctx.html