fgetpos

来自cppreference.com
< c‎ | io
在标头 <stdio.h> 定义
int fgetpos( FILE*          stream, fpos_t*          pos );
(C99 前)
int fgetpos( FILE* restrict stream, fpos_t* restrict pos );
(C99 起)

获得文件流 stream 的文件位置指示器和当前分析状态(若存在),并将它们存储于 pos 所指向的对象。存储的值仅在作为 fsetpos 的输入的情况有意义。

参数

stream-要检验的文件流
pos-指向要存储文件位置指示器到的 fpos_t 对象的指针

返回值

成功时为 0,否则非零值。

示例

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    // 准备保有 4 个 double 类型值的文件
    enum {SIZE = 4};
    FILE* fp = fopen("test.bin", "wb");
    assert(fp);
    int rc = fwrite((double[SIZE]){1.1, 2.2, 3.3, 4.4}, sizeof(double), SIZE, fp);
    assert(rc == SIZE);
    fclose(fp);
 
    // 演示使用 fsetpos 返回到文件起始
    fp = fopen("test.bin", "rb");
    fpos_t pos;
    fgetpos(fp, &pos);               // 存储文件起始于 pos
    double d;
    rc = fread(&d, sizeof d, 1, fp); // 读取首个 double
    assert(rc == 1);
    printf("文件中的第一个值: %.1f\n", d);
    fsetpos(fp,&pos);                // 移动文件位置回文件起始
    rc = fread(&d, sizeof d, 1, fp); // 再次读取首个 double
    assert(rc == 1);
    printf("再次读取文件中的第一个值: %.1f\n", d);
    fclose(fp);
 
    // 演示错误处理
    rc = fsetpos(stdin, &pos);
    if(rc)
        perror("无法对 stdin fsetpos");
}

输出:

文件中的第一个值: 1.1
再次读取文件中的第一个值: 1.1
无法对 stdin fsetpos: Illegal seek

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.21.9.1 The fgetpos function (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.21.9.1 The fgetpos function (第 TBD 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.21.9.1 The fgetpos function (第 336 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.19.9.1 The fgetpos function (第 302 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.9.9.1 The fgetpos function

参阅

返回当前的文件位置指示值
(函数)
将文件位置指示符移动到文件中的指定位置
(函数)
将文件位置指示器移动到文件中的指定位置
(函数)
fgetpos 的 C++ 文档