7

In a scenario using seekg & tellg on a file, I was wondering what is happening under the hood?

    // Open file and get file size
    int myFileSize;
    std::fstream myFile;
    myFile.open(myFileName, std::ios::in|std::ios::binary);
    if (myFile.is_open())
    {
        myFile.seekg(0, std::ios::end);
        myFileSize = myFile.tellg();
        myFile.seekg(0, std::ios::beg);
        myFile.close();
    }

Q1: Is seekg actually walking the entire contents of the file, until it finds some special "EOF character"? Or does it use some other information provided by the filesystem to "know" where the end of the file is?

Q2: seekg is a stream seeking operation. Does that mean that the entire contents of the file must go through the stream?

Forgive me if I only have an rudimentary understanding of how all this works.

Lakey
  • 1,948
  • 2
  • 17
  • 28
  • 1
    Regarding "EOF character": https://latedev.wordpress.com/2012/12/04/all-about-eof/ –  Feb 10 '13 at 00:24

1 Answers1

10

Q1: No. The OS will know the size of the file, and seekg() will use that knowledge - it takes almost identical time whether the file is 1, 100 or 10000000000 bytes long.

Q2: No. It just sets the current "get pointer", which translates to "SetFilePos" or "lseek" in a Windows or Linux system. Nearly all other OS' have similar concepts.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • @Mats Petersson I've been trying to figure out the best way to get the file size, if ifstream already knows the size of the file from the file system, it seems extraordinary to me that we'd have to do something like going to the end of file, getting the size, then returning to the beginning. Or, as some people have claimed that the seekg to end and tellg method are unreliable, to ignore to the end and then get the number of characters read. Then I've seen there's the struct stat method, but I'm not sure how portable this is. Is there no simple method? – Zebrafish Aug 31 '17 at 13:19