Search code examples
c++file-iofstreamifstream

seekg, tellg, zero-based counting and file size


So, I am curious as I've been using this rather useful approach to get the size of the file, but something bothers me. Locking a stream to a file on the file system and

fileStream.seekg(0, std::ios::beg);
int beginning = fileStream.tellg();

yields 0. That's to be expected, we use the benefits of zero-based counting. What is interesting to me is that a file of 512 bytes would have positions in the range of [0, 511], therefore, returning the value of

fileStream.seekg(0, std::ios::end);
int end = (int)fileStream.tellg(); // We don't care for +4GB here

should yield 511 for end, because that's the last byte. The last position within the file loaded. So any buffer used to read in the stream would only get 511 bytes, rather than 512 bytes.

But it works, so you can see my confusion. What gives? I'm at a loss. Where does the +1 come?


Solution

  • After,

    fileStream.seekg(0, std::ios::end);
    

    the file pointer is position just after the last byte (#511). This is what the number 512 indicates. Here, 511 would mean just before the last byte.

    Let's consider a file that's two bytes long:

    • position 0 is before the first byte;
    • position 1 is before the second byte;
    • position 2 is before the (non-existent) third byte, i.e. at the end of the file.