头文件:#include <sys/types.h> #include <unistd.h>
原型 off_t lseek(int fd, off_t offset, int whence)
int fd --> 文件描述符
off_t offset --> 偏移量
int whence --> 偏移位置
SEEK_SET - 从文件头向后偏移
SEEK_CUR - 从当前位置向后偏移
SEEK_END - 从文件尾部向后偏移
返回值
较文件起始位置向后的偏移量
允许超过文件结尾设置偏移量,文件会因此被拓展。
失败返回 -1
应用
拓展文件空间:只能向后拓展,不能向前拓展。
获取文件长度
lseek(fd, 0, SEEK_END);
返回值即为文件长度
案例:
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd;
fd = open("aa.txt",O_RDONLY);
if(fd == -1)
{
perror("error.");
exit(1);
}
int len = lseek(fd,0,SEEK_END);//求文件长度
printf("len = %d.\n",len);
int ret =lseek(fd,2000,SEEK_END); //向后拓展2000字节
printf("ret = %d.\n",ret);
write(fd,"a",1);//使用lseek做文件拓展,结束时必须要加上一次写操作。
close(fd);
return 1;
}