1) fseek和lseek
fseek用来获取或者设置文件流(文件指针)的位置。 FILE *fp;
lseek用来获取或者设置文件指针的位置, int 类型指针
1.1 用open 和 close 打开、关闭文件,对应用 lseek 操作 int 类型指针,示例:
#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;
}
// 拓展文件的长度 增加100个字节
int ret = lseek(fd, 100, SEEK_END);
if(ret == -1) {
perror("lseek");
return -1;
}
// lseek仅仅为移动指针
// 若想真正实现拓展,要写入一个空数据
write(fd, " ", 1);
// 关闭文件
close(fd);
return 0;
}
1.2 用fopen和 fclose 打开、关闭文件,对应用 fseek操作 FILE *fp ,示例:
#include
main()
{
FILE * stream;
long offset;
fpos_t pos;
stream = fopen("/etc/passwd", "r");
fseek(stream, 5, SEEK_SET);
printf("offset = %d\n", ftell(stream));
rewind(stream);
fgetpos(stream, &pos);
printf("offset = %d\n", pos);
pos = 10;
fsetpos(stream, &pos);
printf("offset = %d\n", ftell(stream));
fclose(stream);
}
2 ) 来源说明:
标准C库中的fseek函数。需要包含:
#include <stdio.h>
Linux系统的lseek函数。需要包含:
#include <sys/types.h>
#include <unistd.h>