Namespaces
Variants

std:: fsetpos

From cppreference.net
< cpp ‎ | io ‎ | c
定义于头文件 <cstdio>
int fsetpos ( std:: FILE * stream, const std:: fpos_t * pos ) ;

根据 pos 所指向的值,设置 C 文件流 stream 的文件位置指示符及多字节解析状态(如果存在)。

除了建立新的解析状态和位置外,调用此函数会撤销 std::ungetc 的效果,并清除已设置的文件结束状态。

如果发生读取或写入错误,流的错误指示器( std::ferror )将被设置。

目录

参数

stream - 要修改的文件流
pos - 指向 fpos_t 对象的指针,该对象通过在与同一文件关联的流上调用 std::fgetpos 获得

返回值

0 表示成功,非零值表示失败。同时,在失败时会设置 errno

注释

在宽流中定位到非结尾位置后,下一次调用任何输出函数可能导致文件剩余部分变为未定义状态,例如通过输出不同长度的多字节序列。

示例

#include <cstdio>
#include <cstdlib>
int main()
{
    // 准备浮点数值数组
    const int SIZE = 5;
    double A[SIZE] = {1., 2., 3., 4., 5.};
    // 将数组写入文件
    std::FILE * fp = std::fopen("test.bin", "wb");
    std::fwrite(A, sizeof(double), SIZE, fp);
    std::fclose(fp);
    // 将值读入数组B
    double B[SIZE];
    fp = std::fopen("test.bin", "rb");
    std::fpos_t pos;
    if (std::fgetpos(fp, &pos) != 0)      // 当前位置:文件起始处
    {
       std::perror("fgetpos()");
       std::fprintf(stderr, "fgetpos() failed in file %s at line # %d\n",
                    __FILE__, __LINE__-3);
       std::exit(EXIT_FAILURE);
    }
    int ret_code = std::fread(B, sizeof(double), 1, fp);      // 读取一个值
    // 当前位置:读取一个值后
    std::printf("%.1f; read count = %d\n", B[0], ret_code);   // 打印一个值和ret_code
    if (std::fsetpos(fp, &pos) != 0)   // 重置当前位置到文件起始处
    {
       if (std::ferror(fp))
       {
          std::perror("fsetpos()");
          std::fprintf(stderr, "fsetpos() failed in file %s at line # %d\n",
                       __FILE__, __LINE__-5);
          std::exit(EXIT_FAILURE);
       }
    }
    ret_code = std::fread(B, sizeof(double), 1, fp);         // 重新读取第一个值
    std::printf("%.1f; read count = %d\n", B[0], ret_code);  // 打印一个值和ret_code
    std::fclose(fp);
    return EXIT_SUCCESS; 
}

输出:

1.0; read count = 1
1.0; read count = 1

参见

获取文件位置指示器
(函数)
返回当前文件位置指示器
(function)
将文件位置指示器移动到文件中的特定位置
(函数)
C 文档 for fsetpos