linux中lseek函数
函数原型
off_t lseek(int fd, off_t offset, int whence);
lseek函数:移动文件指针;获取文件长度;文件拓展(只能向后拓展)
其中:fd:要操作文件描述符; offset:是相对于whence(基准)的偏移量;whence:可以是SEEK_SET(文件指针开始),SEEK_CUR(文件指针当前位置),SEEK_END(文件指针尾)
**返回值:**文件读写指针距文件开头的字节大小,出错,返回-1
具体使用见代码lseek.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int fd = open("aa",O_RDWR);
if(fd==-1)
{
perror("open file");
exit(1);
}
//获取文件长度(大小)
int ret = lseek(fd, 0, SEEK_END);
printf("file length = %d\n",ret);//file length = 2015
//文件拓展,只能往后拓展
ret = lseek(fd, 2000, SEEK_END);
printf("return value %d\n",ret);//return value 4015
//实现文件拓展,需要再最后一次写操作,随便写什么东西都可以
write(fd, "a", 1);
close(fd);
return 0;
}