C ++如何添加/减去tellp(),tellg()返回 [英] C++ how to add/subtract tellp(), tellg() return
问题描述
说我想要得到两个tellp()输出之间的差异(int)。
Say I wanted to get the difference (in int) between two tellp() outputs.
如果写一个大文件,tellp所以说它不能安全地存储在一个很长的长。是否有安全的方式来执行这样的操作:
The tellp() output could be huge if a big file is written so it is not safe to say store it inside a long long. Is there a safe way to perform a operation like this:
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。
Here, I know that the difference between end and start can definitely fit in an int. But end and start itself could be very massive.
推荐答案
的返回类型ofstream :: tellp
(和 ifstream :: tellg
)是 char_traits< char> :: pos_type
。除非你真的需要你的最终结果是 int
,你可能想使用 pos_type
。如果你确实需要你的最终结果作为 int
,你仍然可能想存储中间值在 pos_type
s,然后减去结果并将结果转换为 int
。
The return type from ofstream::tellp
(and ifstream::tellg
) is a char_traits<char>::pos_type
. Unless you really need your final result to be an int
, you probably want to use pos_type
throughout. If you do need your final result as an int
you still probably want to store the intermediate values in pos_type
s, then do the subtraction and cast the result to 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;
这篇关于C ++如何添加/减去tellp(),tellg()返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!