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

2019-07-23 17:18发布

问题:

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;