C 库 - fgetpos() 函数



C 库的 fgetpos(FILE *stream, fpos_t *pos) 函数获取流的当前文件位置,并将其写入 pos。它将位置存储在一个 fpos_t 类型的变量中。当您需要保存文件中的特定位置并在以后返回到该位置时,此函数很有用。

语法

以下是 C 库 fgetpos() 函数的语法:

int fgetpos(FILE *stream, fpos_t *pos);

参数

此函数接受两个参数:

  • FILE *stream: 指向 FILE 对象的指针,用于标识流。
  • fpos_t *pos: 指向 fpos_t 类型对象的指针,存储位置。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

fgetpos() 函数在成功时返回 0,失败时返回非零值。

示例 1:简单的获取位置

此示例演示如何获取并打印文件中的当前位置。

以下是 C 库 fgetpos() 函数的示例。

#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("Hello, World!", file); fpos_t pos; // Get the current file position if (fgetpos(file, &pos) != 0) { perror("fgetpos failed"); fclose(file); return 1; } printf("Current position: %ld\n", (long)pos); fclose(file); return 0; }

输出

以上代码将“Hello, World!”写入文件并获取位置,该位置为 13,因为“Hello, World!”包括空格和标点符号在内共有 13 个字符。

Current position: 13

示例 2:在文件中读取和倒回

在此示例中,它演示了如何从文件中读取数据、保存位置,然后倒回到保存的位置。

#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w+"); if (file == NULL) { perror("Failed to open file"); return 1; } fputs("Line 1\nLine 2\nLine 3\n", file); fpos_t pos; // Rewind to the start of the file rewind(file); char buffer[20]; fgets(buffer, sizeof(buffer), file); printf("First read: %s", buffer); // Save the current position after reading the first line if (fgetpos(file, &pos) != 0) { perror("fgetpos failed"); fclose(file); return 1; } fgets(buffer, sizeof(buffer), file); printf("Second read: %s", buffer); // Return to the saved position if (fsetpos(file, &pos) != 0) { perror("fsetpos failed"); fclose(file); return 1; } fgets(buffer, sizeof(buffer), file); printf("Re-read after fsetpos: %s", buffer); fclose(file); return 0; }

输出

执行以上代码后,它将多行写入文件,读取第一行,保存位置,读取第二行,然后返回到保存的位置并再次读取第二行。

First read: Line 1
Second read: Line 2
Re-read after fsetpos: Line 2
广告