fseek for fd(int fd 而不是 FILE)

作者:编程家 分类: c++ 时间:2025-11-04

一篇关于 `fseek` 函数在处理 `int fd` 文件描述符的文章,以下是案例代码和相应的文章:

c

#include

#include

#include

#include

int main() {

int fd = open("example.txt", O_RDONLY);

if (fd == -1) {

perror("Error opening file");

return 1;

}

off_t offset = lseek(fd, 0, SEEK_END);

if (offset == -1) {

perror("Error seeking file");

close(fd);

return 1;

}

printf("File size: %ld bytes\n", offset);

offset = lseek(fd, 0, SEEK_SET);

if (offset == -1) {

perror("Error seeking file");

close(fd);

return 1;

}

char buffer[100];

ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);

if (bytesRead == -1) {

perror("Error reading file");

close(fd);

return 1;

}

buffer[bytesRead] = '\0';

printf("File content:\n%s\n", buffer);

close(fd);

return 0;

}

---

在处理文件时,`fseek` 函数是一个常用的函数,它可以在文件中定位到指定位置。然而,通常我们将 `fseek` 函数与 `FILE*` 类型的指针一起使用,但我们也可以使用 `int fd` 类型的文件描述符来操作文件。本文将介绍如何使用 `fseek` 函数处理 `int fd` 文件描述符,并提供一个简单的示例代码来说明其用法。

## `fseek` 函数简介

`fseek` 函数是一个用于定位文件指针位置的函数,可以将文件指针移动到文件的任意位置。它的原型如下:

c

int fseek(FILE *stream, long int offset, int origin);

其中,`stream` 是一个指向 `FILE` 对象的指针,`offset` 是要移动的字节数,`origin` 是起始位置。`origin` 可以取以下三个值之一:

- `SEEK_SET`:相对于文件开头

- `SEEK_CUR`:相对于当前位置

- `SEEK_END`:相对于文件结尾

## 使用 `fseek` 处理 `int fd`

在使用 `fseek` 函数处理 `int fd` 文件描述符时,我们需要使用 `lseek` 函数来代替。`lseek` 函数的原型如下:

c

off_t lseek(int fd, off_t offset, int whence);

其中,`fd` 是文件描述符,`offset` 是要移动的字节数,`whence` 是起始位置,与 `fseek` 函数的 `origin` 参数相同。

## 示例代码

下面的示例代码演示了如何使用 `fseek` 函数处理 `int fd` 文件描述符。

c

#include

#include

#include

#include

int main() {

int fd = open("example.txt", O_RDONLY);

if (fd == -1) {

perror("Error opening file");

return 1;

}

off_t offset = lseek(fd, 0, SEEK_END);

if (offset == -1) {

perror("Error seeking file");

close(fd);

return 1;

}

printf("File size: %ld bytes\n", offset);

offset = lseek(fd, 0, SEEK_SET);

if (offset == -1) {

perror("Error seeking file");

close(fd);

return 1;

}

char buffer[100];

ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);

if (bytesRead == -1) {

perror("Error reading file");

close(fd);

return 1;

}

buffer[bytesRead] = '\0';

printf("File content:\n%s\n", buffer);

close(fd);

return 0;

}

---

示例代码解析

在上述示例代码中,我们首先使用 `open` 函数打开名为 `example.txt` 的文件,并将返回的文件描述符保存在 `fd` 变量中。如果返回的文件描述符为 -1,则表示打开文件时发生错误,我们将打印错误信息并返回。

接下来,我们使用 `lseek` 函数将文件指针移动到文件末尾,通过将 `offset` 参数设置为 0,`whence` 参数设置为 `SEEK_END` 来实现。`lseek` 函数返回文件指针的新位置,我们将其保存在 `offset` 变量中,并打印文件的大小。

然后,我们使用 `lseek` 函数将文件指针移动到文件开头,通过将 `offset` 参数设置为 0,`whence` 参数设置为 `SEEK_SET` 来实现。

接下来,我们使用 `read` 函数从文件中读取内容,将其存储在 `buffer` 数组中。我们将读取的字节数保存在 `bytesRead` 变量中,并在读取结束后,将 `buffer` 数组的最后一个元素设置为字符串结束符 `\0`,以便将其作为字符串输出。

最后,我们使用 `close` 函数关闭文件描述符,释放资源。

通过以上示例代码,我们可以使用 `lseek` 函数处理 `int fd` 文件描述符,实现文件的定位和读取操作。