Programming of the file with the IO Linux (three): the lseek () to create empty

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

A, lseek () system call

Function description:

By specifying the relative to the start position, number of bytes at the end of the current position or location of the relocation of CURP, depending on the lseek () function in the specified location

The function prototype:

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

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

Explanation of parameters:

fd: The file descriptor

offset: The offset value, which can be positive or negative, negative to move forward

whence: The starting position of the search, there are three options:

(1).SEEK_SET: the current position to the beginning of the file, a new location for the shift size
(2).SEEK_CUR: current position to position the file pointer, a new location for the current position and offset size
(3).SEEK_END: current position is at the end of the file, a new location for the offset amount

Return value: migration file new value

Two, using lseek () produced empty file(hole)

Explain:

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.

The program code:

 

#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;
}

 

Test results:

QQ截图20130710133529

The program creates a hole file, Then write to the ” hello” character, In the use of the lseek system calls from current position offset to 1024*1024*1024 and then written ” world” character, Ls displays the file size is 1.1G, In fact, it did not take so much disk space, Du showed that the hole file is only 8K, The system only store some information, Use it to show how many \0, When we use cat to view the contents of the file and see only hello, Because the file is too large to the final world that cannot see the Empress Dowager, But when we use the OD command to see, You can find a lot of \0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Stanford at November 12, 2013 - 8:19 PM