函数名称:lseek
函数原型:off_t lseek(int fildes, off_t offset, int whence);
函数功能:显式地为一个打开的文件设置其偏移量
返回值:若成功则返回新的文件偏移量,若出错则返回-1
头文件:#include <sys/types.h>
#include <unistd.h>
参数 offset 的含义取决于参数 whence:
1. 如果 whence 是 SEEK_SET ,文件偏移量将被设置为 offset。
2. 如果 whence 是 SEEK_CUR ,文件偏移量将被设置为 cfo 加上 offset,
offset 可以为正也可以为负。
3. 如果 whence 是 SEEK_END ,文件偏移量将被设置为文件长度加上 offset,
offset 可以为正也可以为负。
demo1:
#include <stdio.h> /*for fprintf*/
#include <unistd.h> /*for read write*/
#include <sys/types.h>/*for open*/
#include <sys/stat.h> /*for open*/
#include <fcntl.h> /*for open*/
#include <stdlib.h> /*for EXIT_FAILURE*/
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(){
int fd;
fd=open("test.txt",O_RDONLY);
if(fd==-1){
ERR_EXIT("open error");
}
char buf[1024]={0};
int ret = read(fd,buf,5);
if(ret==-1){
ERR_EXIT("read error");
}
printf("buf=%s\n",buf);
ret=lseek(fd,0,SEEK_CUR);
if(ret==-1){
ERR_EXIT("lseek error");
}
printf("current offset=%d\n",ret);
return 0;
}
demo2:在1024*1024*1024的位置开始写进去hello五个字符:
#include <stdio.h> /*for fprintf*/
#include <unistd.h> /*for read write*/
#include <sys/types.h>/*for open*/
#include <sys/stat.h> /*for open*/
#include <fcntl.h> /*for open*/
#include <stdlib.h> /*for EXIT_FAILURE*/
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(){
int fd;
umask(0);
fd=open("hole.txt",O_WRONLY|O_CREAT,0644);
if(fd==-1){
ERR_EXIT("open error");
}
int ret =lseek(fd,1024*1024*1024,SEEK_CUR);
if(ret==-1){
ERR_EXIT("lseek error");
}
write(fd,"hello",5);
close(fd);
return 0;
}
生成的hole.txt文件: