C语言如何实现lseek
时间: 2024-02-16 21:04:49 浏览: 22
在 C 语言中,可以使用 `lseek()` 函数实现文件指针的移动。该函数的原型如下:
```c
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
```
其中,`fd` 表示文件描述符,`offset` 表示相对于 `whence` 的偏移量,`whence` 表示起点位置,有以下三种选项:
- `SEEK_SET`:表示从文件开头开始计算偏移量;
- `SEEK_CUR`:表示从当前位置开始计算偏移量;
- `SEEK_END`:表示从文件结尾开始计算偏移量。
使用 `lseek()` 函数可以实现文件指针的移动,例如:
```c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return -1;
}
off_t offset = lseek(fd, 0, SEEK_END); // 移动到文件结尾
printf("file size: %ld bytes\n", offset);
offset = lseek(fd, -5, SEEK_CUR); // 向前移动 5 个字节
printf("current position: %ld\n", offset);
close(fd);
return 0;
}
```
上述代码中,首先使用 `open()` 函数打开一个文件,并获取到它的文件描述符 `fd`。然后使用 `lseek()` 函数将文件指针移动到文件结尾,并打印出文件大小。接着使用 `lseek()` 函数将文件指针向前移动 5 个字节,并打印出当前位置。最后使用 `close()` 函数关闭文件。