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

倖福魔咒の 提交于 2019-12-12 17:20:52

问题


Say I wanted to get the difference (in int) between two tellp() outputs.

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;

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.


回答1:


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_types, 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;


来源:https://stackoverflow.com/questions/16825351/c-how-to-add-subtract-tellp-tellg-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!