ftell
From cppreference.net
File input/output
| Types and objects | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<stdio.h>
|
||
|
long
ftell
(
FILE
*
stream
)
;
|
||
返回文件流 stream 的文件位置指示器。
如果流以二进制模式打开,此函数获取的值为从文件起始位置开始的字节数。
如果流以文本模式打开,此函数返回的值是未指定的,仅作为 fseek() 的输入才有意义。
目录 |
参数
| stream | - | 要检查的文件流 |
返回值
成功时返回文件位置指示符,若发生失败则返回 - 1L 。
发生错误时, errno 变量会被设置为实现定义的正数值。
注释
在 Windows 系统上,可使用
_ftelli64
来处理大于 2 GiB 的文件。
示例
演示带错误检查的
ftell()
用法。将若干浮点数值写入文件后从文件读取。
运行此代码
#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函数(页码:303-304)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.9.9.4 ftell 函数
参考
|
获取文件位置指示器
(函数) |
|
|
将文件位置指示器移动到文件中的特定位置
(函数) |
|
|
将文件位置指示器移动到文件中的特定位置
(函数) |
|
|
C++ documentation
for
ftell
|
|