lseek
是C语言中的一个函数,用于在文件中移动当前读/写位置。
它的函数原型如下:
#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 <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("file.txt", O_RDONLY); // 打开一个文本文件以只读方式
if (fd == -1) {
perror("open");
return 1;
}
off_t new_offset = lseek(fd, 10, SEEK_SET); // 将读/写位置移到距离文件起始点10个字节处
if (new_offset == -1) {
perror("lseek");
close(fd);
return 1;
}
char buffer[256];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer)); // 读取从当前位置开始的内容
if (bytes_read == -1) {
perror("read");
close(fd);
return 1;
}
printf("%.*s\n", (int)bytes_read, buffer); // 打印读取的内容
close(fd);
return 0;
}
上述示例中,首先使用open
函数打开一个文本文件(以只读方式)。然后使用lseek
将读/写位置移动到距离文件起始点10个字节处。接下来使用read
函数从当前位置开始读取一定数量的数据,并打印出来。最后通过close
关闭文件描述符。
请注意,在实际使用时需要进行错误检查,确保操作成功。
内容由零声教学AI助手提供,问题来源于学员提问