Chinaunix首页 | 论坛 | 博客
  • 博客访问: 812202
  • 博文数量: 92
  • 博客积分: 1498
  • 博客等级: 上尉
  • 技术积分: 993
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-18 18:31
文章分类

全部博文(92)

文章存档

2013年(2)

2012年(3)

2011年(3)

2010年(61)

2009年(23)

分类: LINUX

2010-07-20 21:41:18

今天看到lseek函数的时候,man lseek 结果如下:
The lseek() function allows the file offset to be set beyond the end of
the file (but this does not change the size of the file).  If  data  is
later written at this point, subsequent reads of the data in the gap 
(a "hole") return null bytes ('\0') until data is  actually  written  into
the gap.

这句话的意思就是lseek可以将只想文件的指针随意移动,甚至可以移除当前文件的大小,因此就延长了文
件大小,这是,如果再从当前指针处写入数据的话,此前跳过的部分全部使用'\0'补充。这样就在文件中
就形成了一个类似于空洞的东西。我们就称之为空洞,"hole"。

下面这个就是一个例子,首先创建一个文件"hole.txt",先向里面写入"the start",然后向后移动32个字节,再开始填充"the end",这样就形成一个所谓的空洞文件。

/*使用lseek函数构建空洞文件*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main(void)
{
  int fd = -1,i;
  ssize_t size = -1;
  off_t offset = -1;
  /*存放数据的缓冲区*/
  char buf1[]="the start";
  char buf2[]="the end";
  /*文件名*/
  char filename[] = "hole.txt";
  int len = 8;
  
  /*创建文件hole.txt*/
    fd = open(filename,O_RDWR|O_CREAT,S_IRWXU);
    if(-1 == fd){
        /*创建文件失败*/
     return -1;
    }    

    /*将buf1中的数据写入到文件Hole.txt中*/
    size = write(fd, buf1,len);
    if(size != len){
        /*写入数据失败*/
        return -1;    
    }
    
    /*设置文件偏移量为绝对值的32*/
    offset = lseek(fd, 32, SEEK_SET);
    if(-1 == offset){
        /*设置失败*/
        return -1;
    }
    /*将buf2中的数据写入到文件hole.txt中*/
    size = write(fd, buf2,len);
    if(size != len){
        /*写入数据失败*/
        return -1;    
    }
        
    /*关闭文件*/
    close(fd);

    return 0;
}




这里的结果如何查看我们生成的是一个空洞文件呢?可以使用十六进制工具od查看生成的hole.txt内容如下:
zhou@zhou:~/test$ od -c hole.txt 
0000000   t   h   e       s   t   a   r  \0  \0  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
0000040   t   h   e       e   n   d  \0
0000050

其中0~8位置由"the start"填充,8~32位置上均为'\0',即进行偏移造成的空洞,33~39是由"the end"填充。

阅读(2315) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~