linux下lseek函数怎么使用

   2025-03-15 8090
核心提示:lseek函数用于设置文件指针的偏移量。其函数原型为:#include unistd.hoff_t lseek(int fd, off_t offset, int whence);参数说明

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

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言