• APUE 第4章: cp命令实现,同时去除文件中的空洞


    在apue第65页有一个用lseek函数制造文件空洞的程序,贴在下面:

    #include "apue.h"
    #include

    char buf1[] = "abcdefghij";
    char buf2[] = "ABCDEFGHIJ";

    int main(void){
        int fd;
        if((fd = creat("file.hole", FILE_MODE)) <0)
            err_sys("creat error");

        if(write(fd, buf1, 10)!=10)
            err_sys("buf1 write error");

        if(lseek(fd, 16384, SEEK_SET) == -1)
            err_sys("lseek error");

        if(write(fd, buf2, 10)!=10)
            err_sys("buf2 write error");

        exit(0);
    }


    lseek指针往后偏移16384个字节,里面都是'\0'.:

    linux@linux:~/apue/c4$ od -c ../c3/file.hole
    0000000   a   b   c   d   e   f   g   h   i   j  \0  \0  \0  \0  \0  \0
    0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
    *
    0040000   A   B   C   D   E   F   G   H   I   J
    0040012
     

    apue第4章第6题: 编写一个类似cp(1)的程序,它复制包含空洞的文件,但不将字节0写到输出文件中去.

    分析:用read函数读1个字节,写入到buf中去,如果buf[0] == '\0' ,丢弃.

    实现如下:

    1. #include
    2. #include
    3. #include
    4. #include
    5. int main(int argc, const char *argv[])
    6. {
    7. char buf[1];
    8. int read_fd;
    9. int write_fd;
    10. if(argc != 2){
    11. perror("input");exit(1);
    12. }
    13. if((read_fd = open(argv[1], O_RDONLY)) < 0){
    14. perror("read open");exit(1);
    15. }
    16. if((write_fd = open("newfile", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR |S_IWUSR |S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH))<0){
    17. perror("write open");exit(1);
    18. }
    19. while(read(read_fd, buf, 1)==1){
    20. if(buf[0] == '\0') continue;
    21. write(write_fd, buf,1);
    22. }
    23. close(read_fd);
    24. close(write_fd);
    25. return 0;
    26. }

    实现的结果

    原来:
    linux@linux:~/apue/c4$ od -c ../c3/file.hole
    0000000   a   b   c   d   e   f   g   h   i   j  \0  \0  \0  \0  \0  \0
    0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
    *
    0040000   A   B   C   D   E   F   G   H   I   J
    0040012

    现在
    linux@linux:~/apue/c4$ cat newfile
    abcdefghijABCDEFGHIJ   linux@linux:~/apue/c4$ ls -l newfile
    -rw-rw-r-- 1 linux linux 20 Jul 27 21:43 newfile
     

    用到的知识点 p 99 - p 100 ,read读到的空洞为字节0

  • 相关阅读:
    [附源码]java毕业设计图书管理系统
    私有继承和虚函数私有化能用么?
    Java基础用Date类编写万年历
    高性能分布式No SQL数据库Aerospike——常用工具使用
    flink sql text to jobGraph
    【图像处理】图像基础滤波处理:盒式滤波、均值滤波、高斯滤波、中值滤波、双边滤波
    使用Redis源码探究字符串的实现
    一分钟带你了解音视频开发进阶(先收藏了)
    2022牛客蔚来杯第四场 N K D H A
    【JavaSE】方法的使用
  • 原文地址:https://blog.csdn.net/m0_47161778/article/details/126028345