1. 程式人生 > >檔案I/O-002.lseek空洞檔案

檔案I/O-002.lseek空洞檔案

/*
製造空洞檔案,空洞的部分寫為0
od -c file.hole
od觀察檔案的實際內容,od -c 以字元形式列印
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
char buf1[]="abcdefghij";
char buf2[]="ABCDEFGHIJ";
int main()
{
    int fd;
	fd=open("file.hole",O_CREAT|O_RDWR|O_TRUNC,0777);
	if(fd==-1)
	    printf("open fail\n");
	
	if(write(fd,buf1,10) != 10)
	{
	    printf("write buf1 fail\n");
	}
	if(lseek(fd,16384,SEEK_SET) == -1)
	{
	    printf("lseek fail\n");
	}
	if(write(fd,buf2,10) != 10)
	{
	    printf("write buf2 fail\n");
	}
	exit(0);
}
/*
ls -l file.hole 
-rwxrwxrwx 1 root root 16394 09-27 14:05 file.hole

od -c file.hole      觀察實際內容
0000000   a   b   c   d   e   f   g   h   i   j  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0040000   A   B   C   D   E   F   G   H   I   J
0040012
*/