fgetpos
来自 cppreference.com
定义在头文件 <stdio.h> 中 |
||
(直到 C99) | ||
(自 C99) | ||
获取文件流 stream
的文件位置指示器和当前解析状态(如果有),并将它们存储在 pos
指向的对象中。 存储的值只有作为 fsetpos 的输入才有意义。
内容 |
[编辑] 参数
stream | - | 要检查的文件流 |
pos | - | 指向 fpos_t 对象的指针,用于存储文件位置指示器 |
[编辑] 返回值
0 成功时,否则为非零值。
[编辑] 示例
运行此代码
#include <stdio.h> #include <stdlib.h> #include <assert.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