How to create a file with file holes?

后端 未结 4 1836
故里飘歌
故里飘歌 2020-12-02 14:58

File holes are the empty spaces in file, which, however, doesn\'t take up any disk space and contains null bytes. Therefore, the file size is larger than its actual size on

4条回答
  •  长情又很酷
    2020-12-02 15:19

    The problem is carefully discussed in section 3.6 of W.Richard Stevens famous book "Advanced Programming in the UNIX Environment" (APUE for short). The lseek funstion included in unistd.h is used here, which is designed to set an open file's offset explicitly. The prototype of the lseek function is as follows:

    off_t lseek(int filedes, off_t offset, int whence);
    

    Here, filedes is the file descriptor, offset is the value we are willing to set, and whence is a constant set in the header file, specifically SEEK_SET, meaning that the offset is set from the beginning of the file; SEEK_CUR, meaning that the offset is set to its current value plus the offset in the arguement list; SEEK_END, meaning that the file's offset is set the the size of the file plus the offset in the arguement list.

    The example to create a file with holes in C under UNIX like OSs is as follows:

    /*Creating a file with a hole of size 810*/
    #include 
    
    /*Two strings to write to the file*/    
    char buf1[] = "abcde";
    char buf2[] = "ABCDE";
    
    int main()
    {
        int fd; /*file descriptor*/
    
        if((fd = creat("file_with_hole", FILE_MODE)) < 0)
            err_sys("creat error");
        if(write(fd, buf1, 5) != 5)
            err_sys("buf1 write error");
        /*offset now 5*/
    
        if(lseek(fd, 815, SEEK_SET) == -1)
            err_sys("lseek error");
        /*offset now 815*/
    
        if(write(fd, buf2, 5) !=5)
            err_sys("buf2 write error");
        /*offset now 820*/
    
        return 0;
    }
    

    In the code above, err_sys is the function to deal with fatal error related to a system call.

提交回复
热议问题