接口:off_t lseek(int fd, off_t offset, int whence);
头文件:
#include<sys/types.h>
#include<unistd.h>
一、参数
1.fd:要操作的文件对应的文件描述符
2.offset:相对于whence的偏移量
3.whence:可以为SEEK_SET(0),SEEK_CUR(1),SEEK_END(2);
SEEK_SET:将读写位置移动到文件头后再增加offset个字节
SEEK_CUR:将读写位置移动到当前指定位置后再增加offset个字节
SEEK_END:将读写位置移动到文件结尾后再增加offset个字节
二、返回值:成功则返回当前读写位置,即目前的文件指针距文件开头有多少个字节;失败则返回-1
三、功能:
1.设置文件指针的位置
2.拓展文件大小
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc, char* argv[])
{
//创建文件
int fd = open("test.txt", O_CREAT | O_RDWR, 0664);
if(fd == -1){
perror("open file");
exit(1);
}
//写入数据到打开的文件
char buf[] = {"hello,linux,write!"};
int count = write(fd, buf, sizeof(buf));
if(count == -1){
perror("write file");
exit(1);
}
int length = lseek(fd, 0, SEEK_END); //设置文件指针到结尾,可以获取文件的当前大小
if(length == -1){
perror("lseek file");
exit(1);
}
printf("before file length = %d\n", length);
length = lseek(fd, 1000,SEEK_END); //拓展文件大小,当前文件指针位置为拓展前结尾位置+1000,1000为拓展量
if(length == -1){
perror("lseek file");
exit(1);
}
printf("after file length = %d\n", length);
write(fd, "zhang", 5); //从当前文件指针位置,再写5个字节到文件
length = lseek(fd, 0, 2);
printf("file bytes: %d\n",length);
close(fd);
return 0;
}
结果:
before file length = 19
after file length = 1019
file bytes: 1024