c++如何加/减tellg(), tellg()返回

C++ how to add/subtract tellp(), tellg() return

本文关键字:tellg 返回 何加 c++      更新时间:2023-10-16

假设我想获得两个tell()输出之间的差值(以int表示)。

如果写入一个大文件,tell()的输出可能非常大,所以说将它存储在一个long long中是不安全的。是否有一种安全的方法来执行这样的操作:

ofstream fout;
fout.open("test.txt",ios::out | ios::app);
int start = fout.tellp();
fout<<"blah blah "<<100<<","<<3.14;
int end = fout.tellp();
int difference = end-start;

在这里,我知道end和start之间的区别完全可以放在int类型中。但是end and start本身可能非常大

ofstream::tellp(和ifstream::tellg)返回类型为char_traits<char>::pos_type。除非您确实需要最终结果是int,否则您可能希望始终使用pos_type。如果你确实需要最终结果为int,你可能仍然希望将中间值存储在pos_type s中,然后进行减法并将结果强制转换为int

typedef std::char_traits<char>::pos_type pos_type;
ofstream fout;
fout.open("test.txt",ios::out | ios::app);
pos_type start = fout.tellp();
fout<<"blah blah "<<100<<","<<3.14;
pos_type end = fout.tellp();
int difference = int(end-start);
// or: pos_type difference = end-start;