linux系统编程之文件与IO:利用lseek()建立空洞文件

1、lseek()系统调用ide

功能说明:函数

经过指定相对于开始位置、当前位置或末尾位置的字节数来重定位 curp,这取决于 lseek() 函数中指定的位置测试

函数原型:this

#include <sys/types.h>
#include <unistd.h>spa

off_t lseek(int fd, off_t offset, int whence);指针

参数说明:code

fd:文件描述符blog

offset:偏移量,该值可正可负,负值为向前移get

whence:搜索的起始位置,有三个选项:原型

(1).SEEK_SET: 当前位置为文件的开头,新位置为偏移量大小
(2).SEEK_CUR: 当前位置为文件指针位置,新位置为当前位置加上偏移量大小
(3).SEEK_END: 当前位置为文件结尾,新位置为偏移量大小

返回值:文件新的偏移值

2、利用lseek()产生空洞文件(hole)

说明:

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.

程序代码:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#define ERR_EXIT(m) \
    do \
    { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)

int main(void)
{
    int fd;
    int ret;
    fd = open("hole.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
    if(fd == -1)
        ERR_EXIT("open error");
    write(fd,"hello",5);
    ret = lseek(fd,1024*1024*1024,SEEK_CUR);
    if(ret == -1)
        ERR_EXIT("lseek error");
    write(fd,"world",5);
    close(fd);
    return 0;
}

测试结果:

QQ20130710133529_thumb

程序建立一个hole文件,而后写入”hello”字符,在利用lseek系统调用从当前位置偏移到1024*1024*1024以后再写入”world”字符,ls显示文件大小为1.1G,实际上它并无占用这么多的磁盘空间,du代表hole文件只有8k,系统只是存储一些信息,用它来表示有多少个\0,当咱们用cat查看文件内容时只看到hello,因为文件太大最后的world太后以至看不到,但当咱们用od命令查看时,能够发现有好多个\0。

相关文章
相关标签/搜索