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。

相關文章
相關標籤/搜索