命名空间
变体
操作

fsetpos

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

格式化输入
 
定义于头文件 <stdio.h>
int fsetpos( FILE* stream, const fpos_t* pos );

根据 pos 指向的值,为文件流 stream 设置文件位置指示器和多字节解析状态(如果有)。

除了建立新的解析状态和位置之外,调用此函数还会撤消 ungetc 的效果,并清除文件结束状态(如果已设置)。

如果发生读取或写入错误,则会设置流的错误指示器 (ferror)。

目录

[编辑] 参数

stream - 要修改的文件流
pos - 指向 fpos_t 对象的指针,用作文件位置指示器的新值

[编辑] 返回值

0 成功时返回 0,否则返回非零值。

[编辑] 注意

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

[编辑] 示例

带有错误检查的 fsetpos

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    // Prepare an array of FP (floating-point) values.
    #define SIZE 5
    double A[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0};
    // Write array to a file.
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A,sizeof(double),SIZE,fp);
    fclose (fp);
 
    // Read the FP values into array B.
    double B[SIZE];
    fp = fopen("test.bin","rb");
    fpos_t pos;
    if (fgetpos(fp, &pos)) // current position: start of file
    {
        perror("fgetpos()");
        fprintf(stderr, "fgetpos() failed in file %s at line # %d\n",
                __FILE__, __LINE__ - 3);
        exit(EXIT_FAILURE);
    }
 
    int ret_code = fread(B,sizeof(double),1,fp); // read one FP value
    // current position: after reading one f-p value
    printf("%.1f; read count = %d\n", B[0], ret_code); // print one FP value and ret_code
 
    if (fsetpos(fp, &pos)) // reset current position to start of file
    {
        if (ferror(fp))
        {
            perror("fsetpos()");
            fprintf(stderr, "fsetpos() failed in file %s at line # %d\n", __FILE__,
                    __LINE__ - 5);
            exit(EXIT_FAILURE);
        }
    }
 
    ret_code = fread(B, sizeof(double), 1, fp); // reread first FP value
    printf("%.1f; read count = %d\n", B[0], ret_code); // print one FP value and ret_code
    fclose(fp);
 
    return EXIT_SUCCESS;
}

可能的输出

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

[编辑] 参考文献

  • C23 标准 (ISO/IEC 9899:2024)
  • 7.21.9.3 fsetpos 函数 (p: TBD)
  • C17 标准 (ISO/IEC 9899:2018)
  • 7.21.9.3 fsetpos 函数 (p: TBD)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.21.9.3 fsetpos 函数 (p: 337)
  • C99 标准 (ISO/IEC 9899:1999)
  • 7.19.9.3 fsetpos 函数 (p: 303)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 4.9.9.3 fsetpos 函数

[编辑] 参见

获取文件位置指示器
(函数) [编辑]
返回当前文件位置指示器
(函数) [编辑]
将文件位置指示器移动到文件中的特定位置
(函数) [编辑]
C++ 文档 关于 fsetpos