需要包含头文件:<sys/types.h> <unistd.h>
off_t lseek(int fd, off_t offset, int whence); 函数原型
函数功能:移动文件读写指针;获取文件长度;拓展文件空间。
在使用该函数之前需要将文件打开! off_t 有符号整型 fd为文件描述符 offset参数指定偏移量 whence参数指定具体从哪个位置开始偏移: SEEK_SET 文件头 SEEK_CUR 当前指针位置 SEEK_END 文件尾(注意文件尾为文件结束符EOF=-1)
返回值:较文件起始位置向后的偏移量(到文件读写指针的位置) 其可以大于当文件读写指针处于文件末尾时的偏移量,此时文件空间被拓展。
获取文件长度: lseek( fd , 0 , SEEK_END); 返回值即为文件长度。
//获取一个文件的长度并且拓展该文件的空间
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>int main( )
{int fd;fd = open("file",O_WRONLY); //打开file文件if( fd == -1 ){perror(" open file " );exit(1);}int length;length = lseek( fd , 0 , SEEK_END ); //获取file文件的长度printf(" The length of the file is %d.\n",length);length=lseek( fd , 3000 , SEEK_END ); //拓展file文件空间,增加3000字节printf(" The length of the file is %d.\n",length); //注意此时文件实质上还没有被拓展,需要在末位写入一些数据int fd1;fd1 = write( fd , "a" , 1); //此时文件才被拓展,在文件末位写入一个字节的数据if( fd1 == -1 ){perror(" write file " );exit(1);}length = lseek( fd , 0 , SEEK_END );printf(" The length of the file is %d, after lengthen.\n",length);int qw;qw = close(fd);if( qw == -1 ){perror( "close file");exit(1);}return 0;
}
[root@localhost work]# vim file
[root@localhost work]# ./rdwr
The length of the file is 64.
The length of the file is 3064.
The length of the file is 3065, after lengthen.
[root@localhost work]# vim rdwr.c
[root@localhost work]# ll file
-rwxrwxrwx. 1 root root 3065 Mar 19 16:54 file //最终文件大小为3065Bytes