/*
标准c库函数
#include <stdio.h>
int fseek(FILE *stream, long offset, int whence);
Linux系统函数
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:
- fd:文件描述符,通过open得到的,通过这个fd操作某个文件
- offset:偏移量
- whence:
SEEK_SET
设置文件指针的偏移量
SEEK_CUR
设置偏移量:当前位置+第二个参数offset的值
SEEK_END
设置偏移量:文件大小+第二个参数offset的值
返回值:返回最终文件指针的位置
作用:
1.移动文件指针到文件头
lseek(fd,0,SEEK_SET)
2.获取当前文件指针的位置
lseek(fd,0,SEEK_CUR)
3.获取文件的长度
lseek(fd,0,SEEK_END)
4.扩展文件的长度,当前文件10b,110b,要增加100个字节,
lseek(fd,100,SEEK_END) //即在文件末尾的位置再偏移100,对文件进行扩展,使其增加100
注意:需要写入一次数据才有用,见下面的例子
*/
#include <sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
int main(){
int fd=open("hello.txt",O_RDWR);
if(fd==-1){
perror("open");
return -1;
}
//扩展文件的长度
int ret=lseek(fd,100,SEEK_END);
if(ret==-1){
perror("open");
return -1;
}
//写入一个空数据,如果不写入一个空数据的话(即没有这行代码),会发现该程序没办法扩展文件的大小
write(fd," ",1);
close(fd);
return 0;
}
//最后文件的大小=原文件大小+100+1(这个1代表的是写入的空数据)
【Linux】lseek函数
最新推荐文章于 2024-04-30 17:02:38 发布