//在linux文件操作中, 文件位移量可以大于文件的当前长度,
//在这种情况下,对该文件的下一次写将延长该文件, //并在文件中构成一个空洞,这一点是允许的。位于文件中但没有写过的字节都被读为 0。 //创建一个有空洞的文件,即文件指针指向末尾后N个字节写内容 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <error.h> #include <errno.h> #include <signal.h> #include <string.h> #define HOLE_FILE "file.hole" int main() { int fd; char buf[] = "Before hole."; char hole[] = "After hole."; fd = open(HOLE_FILE,O_CREAT|O_RDWR,S_IRWXUSR); if(fd < 0) perror("Create file error."); //首先写buf的内容 write(fd,buf,strlen(buf)); //将文件指针从起始位置移动30个字节,超出了文件大小 lseek(fd,30,SEEK_SET); //写入hole的内容 write(fd,hole,strlen(hole)); close(fd); return 0; } 使用od -c 查看文件可以看出空洞 od -c file.hole 0000000 B e f o r e h o l e . \0 \0 \0 \0 0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 A f 0000040 t e r h o l e . 0000051 |