c语言lseek函数如何使用

1172
2023/7/31 20:05:29
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,lseek函数是用于设置文件指针位置的函数。其原型如下:

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

参数说明:

  • fd:文件描述符,用于标识要操作的文件。

  • offset:偏移量,可以是正数、负数或零。

  • whence:参考位置,可以是以下值之一:

  • SEEK_SET:从文件起始位置开始计算偏移量。

  • SEEK_CUR:从当前位置开始计算偏移量。

  • SEEK_END:从文件末尾位置开始计算偏移量。

返回值:返回当前文件指针的位置,失败时返回-1。

使用示例:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDWR); // 打开文件
if (fd == -1) {
perror("open");
return 1;
}
off_t pos = lseek(fd, 0, SEEK_SET); // 设置文件指针位置为文件起始位置
if (pos == -1) {
perror("lseek");
return 1;
}
char buf[100];
ssize_t n = read(fd, buf, sizeof(buf)); // 读取文件内容
if (n == -1) {
perror("read");
return 1;
}
printf("Read: %s\n", buf);
close(fd); // 关闭文件
return 0;
}

上述示例中,首先使用open函数打开文件,并将返回的文件描述符保存到fd变量中。然后,使用lseek函数将文件指针位置设置为文件的起始位置。接着,使用read函数读取文件内容,并将读取的内容打印出来。最后,使用close函数关闭文件。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言的头文件是什么