Linux 拨号vps windows公众号手机端

linux下lseek函数怎么使用

lewis 6年前 (2019-11-17) 阅读数 7 #网络运维
文章标签 linuxlseek

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;
}

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门