假设我想获得两个 tellp() 输出之间的差异(整数)。
如果写入一个大文件,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中。但是结束和开始本身可能非常庞大。
最佳答案
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;
关于C++如何加减tellp(),tellg()返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825351/