Namespaces
Variants

fgetpos

来自 zh.cppreference.net
< c | io
 
 
文件输入/输出
类型和对象
        
函数
文件访问
(C11)
(C11)  
(C95)
无格式输入/输出
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)
(C95)
(C95)

格式化输入
(C11)(C11)(C11)
(C95)(C95)(C95)(C11)(C11)(C11)
(C99)(C99)(C99)(C11)(C11)(C11)
(C99)(C99)(C99)(C11)(C11)(C11)  
直接输入/输出
格式化输出
(C99)(C11)(C11)(C11)(C11)
(C95)(C95)(C95)(C11)(C11)(C11)(C11)  
(C95)(C95)(C95)(C11)(C11)(C11)(C11)
文件位置
错误处理
文件操作
 
定义于头文件 <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成功时返回 0,否则返回非零值。

示例

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    // prepare a file holding 4 values of type 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);

    // demo using fsetpos to return to the beginning of a file
    fp = fopen("test.bin", "rb");
    fpos_t pos;
    fgetpos(fp, &pos);               // store start of file in pos
    double d;
    rc = fread(&d, sizeof d, 1, fp); // read the first double
    assert(rc == 1);
    printf("First value in the file: %.1f\n", d);
    fsetpos(fp,&pos);                // move file position back to the start of the file
    rc = fread(&d, sizeof d, 1, fp); // read the first double again
    assert(rc == 1);
    printf("First value in the file again: %.1f\n", d);
    fclose(fp);

    // demo error handling
    rc = fsetpos(stdin, &pos);
    if (rc)
        perror("could not fsetpos stdin");
}

输出:

First value in the file: 1.1
First value in the file again: 1.1
could not fsetpos stdin: Illegal seek

引用

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

参阅

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