std::ftell
来自cppreference.com
在标头 <cstdio> 定义 | ||
long ftell(std::FILE* stream ); | ||
返回文件流 stream
的文件位置指示器的当前值。
若流以二进制模式打开,则此函数获得的值是距文件起始的字节数。
若流以文本模式打开,则此函数的返回值是未指定的,而且仅若作为 std::fseek 的输入才有意义。
目录 |
[编辑]参数
stream | - | 要检验的文件流 |
[编辑]返回值
成功时为文件位置指示器,若失败出现则为 -1L。失败时亦设置 errno。
[编辑]注解
Windows 中,应使用 _ftelli64
以支持大小超过 2GiB 的文件。
[编辑]示例
演示带有错误检查的 std::ftell()
。在一个文件上写入并读取一些浮点数。
运行此代码
#include <cstdio>#include <cstdlib>#include <iostream> // 如果不满足条件,则输出错误消息并退出程序。void check(bool condition, constchar* func, int line){if(condition)return;std::perror(func);std::cerr<< func <<" failed in file "<< __FILE__ <<" at line # "<< line -1<<'\n';std::exit(EXIT_FAILURE);} int main(){// 准备一个浮点值的数组。constexprint SIZE {5};double A[SIZE]={1.1, 2.2, 3.3, 4.4, 5.5}; // 将数组写入文件。constchar* fname ="/tmp/test.bin"; FILE* file =std::fopen(fname, "wb"); check(file !=NULL, "fopen()", __LINE__); constint write_count =std::fwrite(A, sizeof(double), SIZE, file); check(write_count == SIZE, "fwrite()", __LINE__); std::fclose(file); // 将这些浮点值读入数组 B。double B[SIZE]; file =std::fopen(fname, "rb"); check(file !=NULL, "fopen()", __LINE__); long pos = std::ftell(file);// 文件起始的位置指示器 check(pos !=-1L, "ftell()", __LINE__);std::cout<<"pos: "<< pos <<'\n'; constint read_count =std::fread(B, sizeof(double), 1, file);// 读取一个浮点值 check(read_count ==1, "fread()", __LINE__); pos = std::ftell(file);// 文件起始的位置指示器 check(pos !=-1L, "ftell()", __LINE__);std::cout<<"pos: "<< pos <<'\n';std::cout<<"B[0]: "<< B[0]<<'\n';// 打印一个浮点值 returnEXIT_SUCCESS;}
可能的输出:
pos: 0 pos: 8 B[0]: 1.1
[编辑]参阅
获取文件位置指示器 (函数) | |
移动文件位置指示器到文件中的指定位置 (函数) | |
移动文件位置指示器到文件中的指定位置 (函数) | |
返回输入位置指示器 ( std::basic_istream<CharT,Traits> 的公开成员函数) | |
返回输出位置指示器 ( std::basic_ostream<CharT,Traits> 的公开成员函数) | |
ftell 的 C 文档 |