温馨提示×

linux下lseek函数怎么使用

小亿
101
2023-08-24 19:54:34
栏目: 智能运维

lseek函数用于设置文件指针的偏移量。

其函数原型为:

#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);

参数说明:

  • fd:文件描述符

  • offset:偏移量

  • whence:偏移的起始位置,有以下三个值:

  • SEEK_SET:文件起始位置

  • SEEK_CUR:当前位置

  • SEEK_END:文件末尾位置

函数返回值为新的文件指针位置,若执行失败则返回-1,并设置errno。

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDWR); // 打开文件
if (fd == -1) {
perror("open");
exit(1);
}
off_t offset = lseek(fd, 0, SEEK_END); // 将文件指针定位到文件末尾
if (offset == -1) {
perror("lseek");
exit(1);
}
printf("File size: %ld\n", offset);
close(fd); // 关闭文件
return 0;
}

该示例代码打开一个文件,将文件指针定位到文件末尾,并打印文件大小。

0