需要包含頭文件:<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