C ++如何添加/减去tellp(),tellg()返回

时间:2013-05-29 23:02:45

标签: c++ iostream ofstream

说我想得到两个tellp()输出之间的差异(在int中)。

如果写入一个大文件,则tellp()输出可能很大,因此将其存储在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。但结束和开始本身可能非常庞大。

1 个答案:

答案 0 :(得分:2)

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;