ftell
来自 cppreference.cn
定义于头文件 <stdio.h> |
||
long ftell( FILE* stream ); |
||
返回文件流 stream 的文件位置指示器。
如果流以二进制模式打开,则此函数获得的值是从文件开始处的字节数。
如果流以文本模式打开,则此函数返回的值是未指定的,仅作为 fseek() 的输入才有意义。
内容 |
[编辑] 参数
stream | - | 要检查的文件流 |
[编辑] 返回值
成功时返回文件位置指示器,失败时返回 -1L。
出错时,errno 变量被设置为实现定义的正值。
[编辑] 注解
在 Windows 上,可以使用 _ftelli64
来处理大于 2 GiB 的文件。
[编辑] 示例
演示了带有错误检查的 ftell()
。将一些浮点 (FP) 值写入/读取到文件。
运行此代码
#include <stdio.h> #include <stdlib.h> /* If the condition is not met then exit the program with error message. */ void check(_Bool condition, const char* func, int line) { if (condition) return; perror(func); fprintf(stderr, "%s failed in file %s at line # %d\n", func, __FILE__, line - 1); exit(EXIT_FAILURE); } int main(void) { /* Prepare an array of FP values. */ #define SIZE 5 double A[SIZE] = {1.1, 2.0, 3.0, 4.0, 5.0}; /* Write array to a file. */ const char* fname = "/tmp/test.bin"; FILE* file = fopen(fname, "wb"); check(file != NULL, "fopen()", __LINE__); const int write_count = fwrite(A, sizeof(double), SIZE, file); check(write_count == SIZE, "fwrite()", __LINE__); fclose(file); /* Read the FP values into array B. */ double B[SIZE]; file = fopen(fname, "rb"); check(file != NULL, "fopen()", __LINE__); long int pos = ftell(file); /* position indicator at start of file */ check(pos != -1L, "ftell()", __LINE__); printf("pos: %ld\n", pos); const int read_count = fread(B, sizeof(double), 1, file); /* read one FP value */ check(read_count == 1, "fread()", __LINE__); pos = ftell(file); /* position indicator after reading one FP value */ check(pos != -1L, "ftell()", __LINE__); printf("pos: %ld\n", pos); printf("B[0]: %.1f\n", B[0]); /* print one FP value */ return EXIT_SUCCESS; }
可能的输出
pos: 0 pos: 8 B[0]: 1.1
[编辑] 参考文献
- C23 标准 (ISO/IEC 9899:2024)
- 7.21.9.4 ftell 函数 (p: TBD)
- C17 标准 (ISO/IEC 9899:2018)
- 7.21.9.4 ftell 函数 (p: TBD)
- C11 标准 (ISO/IEC 9899:2011)
- 7.21.9.4 ftell 函数 (p: 337-338)
- C99 标准 (ISO/IEC 9899:1999)
- 7.19.9.4 ftell 函数 (p: 303-304)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.9.9.4 ftell 函数
[编辑] 参见
获取文件位置指示器 (函数) | |
将文件位置指示器移动到文件中的特定位置 (函数) | |
将文件位置指示器移动到文件中的特定位置 (函数) | |
C++ 文档 关于 ftell
|