有“空洞”的文件的C代码实现

来源:互联网 发布:网络上游初始化失败 编辑:程序博客网 时间:2024/06/05 13:21

      最近看apue, 看到了空洞文件的介绍, 颇为好奇, 下面来学习一下。如果你不知道什么是空洞文件, 请去学习apue. 


      下面,我们先来做一个空洞文件:

#include <unistd.h> // unix std#include <stdio.h>  // std io#include <fcntl.h>  // file control#define FILE_MODE   (S_IRUSR | S_IWUSR |S_IRGRP |S_IROTH) // 文件模式char buf1[] = "abcdefghij";char buf2[] = "ABCDEFGHIJ";int main(){    int fd = -1;    if((fd = creat("file.hole", O_CREAT|O_RDWR)) < 0){        perror("creat error\n");exit(1);}    if(10 =! write(fd,buf1,10)){        perror("buf1 write error\n");exit(1);}    if(-1 == lseek(fd, 16384, SEEK_SET)) // 导致文件产生空洞{        perror("lseek error\n");exit(1);}    if(10 != write(fd,buf2,10)){        perror("write buf2 error\n");exit(1);}        close(fd);    return 0;}
      gcc一下, 生成了a.out, ./a.out一下就生成了file.hole文件, 用如下两个命令:

cp file.hole file.hole1

cat file.hole > file.hole2


     然后再ls -l看一下结果, 可知: file.hole和file.hole1完全一致, 即有空洞。 而file.hole2是没有空洞的文件。   有点weird的是: 如果用beyond compare比较, file.hole1和file.hole2居然是完全相同的。 原来: beyond compare在读取有空洞的file.hole1时候, 自动将空洞补为了0, 于是误认为file.hole1和file.hole2相同。



0 0