How to collect and store tellp(), tellg() return t

2019-07-17 11:42发布

问题:

I am writing a program that maintains a linked_list in a file. So I traverse across the file, by using tellp()/tellg() and adding it to a particular long integer(can be seen as an offset) to get to the new location.

An simple example would be

   long next_offset =  sizeof(long) + sizeof(int) .... 
   //like size of all the elements in the record, etc

   curr_node = out.seekg();
   while(curr_node != -1) {
          out.read(...);
          **curr_node.seekg(curr_node.tellp() + next_offset);**
          out.read((char *)&curr_node,sizeof(long));
   }

so here basically I am saving tellp() value as long and dng an long addition, is this fine?? or is there a chance that I might lose some bits when the pos_value gets big???

回答1:

These values returned by tellp/tellg (streampos) are meant to store the maximum file size in the platform you're using, so there's no guarantee they will fit in a long. In fact, they may not fit in a size_t, long long, or whatever is the biggest fundamental type, since disk storage space is usually orders of magnitude larger than address space, and the fundamental types were defined with the later in mind.

But IMO the practical thing to do is not to use another, bigger type unless you're writing a program that really needs to handle huge files (like a DBMS or so), which is a rare case. If the maximum expected size fits in a long, simply put safeguards in your program to refuse to create or handle files bigger than that.

On the other hand, if that's indeed the case that you may have to handle enormous files, then things got a lot more complicated, and a comprehensive answer would be longer.