ftell
来自cppreference.com
| 在标头 <stdio.h> 定义
|
||
| |
||
返回流 stream 的文件位置指示器。
若流以二进制模式打开,则由此函数获得的值是从文件开始的字节数。
若流以文本模式打开,则由此函数返回的值未指定,且仅若作为 fseek() 的输入才有意义。
参数
| stream | - | 要检验的文件流 |
返回值
成功时为文件位置指示器,若失败发生则为 -1L 。
失败时,设 errno 对象为实现定义的正值。
注解
Windows 中,应使用 _ftelli64 以支持大小超过 2GiB 的文件。
示例
演示 ftell() 带错误检查。向文件写出少量浮点数后再从中读取它们。
运行此代码
#include <stdio.h>
#include <stdlib.h>
/* 如果条件不满足,则退出程序并给出错误消息。 */
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)
{
/* 准备浮点数的数组。 */
#define SIZE 5
double A[SIZE] = {1.1, 2.0, 3.0, 4.0, 5.0};
/* 写数组到文件。 */
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);
/* 读取浮点数到数组 B。 */
double B[SIZE];
file = fopen(fname, "rb");
check(file != NULL, "fopen()", __LINE__);
long int pos = ftell(file); /* 位置指示器在文件起始 */
check(pos != -1L, "ftell()", __LINE__);
printf("pos: %ld\n", pos);
const int read_count = fread(B, sizeof(double), 1, file); /* 读取一个浮点数 */
check(read_count == 1, "fread()", __LINE__);
pos = ftell(file); /* 读取一个浮点数后的位置指示器 */
check(pos != -1L, "ftell()", __LINE__);
printf("pos: %ld\n", pos);
printf("B[0]: %.1f\n", B[0]); /* 打印一个浮点数 */
return EXIT_SUCCESS;
}
可能的输出:
pos: 0
pos: 8
B[0]: 1.1
引用
- C23 标准(ISO/IEC 9899:2024):
- 7.21.9.4 The ftell function (第 TBD 页)
- C17 标准(ISO/IEC 9899:2018):
- 7.21.9.4 The ftell function (第 TBD 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.21.9.4 The ftell function (第 337-338 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.19.9.4 The ftell function (第 303-304 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.9.9.4 The ftell function
参阅
| 获取文件位置指示器 (函数) | |
| 将文件位置指示符移动到文件中的指定位置 (函数) | |
| 将文件位置指示器移动到文件中的指定位置 (函数) | |
ftell 的 C++ 文档
| |