Lakey
Lakey

Reputation: 2068

How does seekg find the end of the file?

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.

Upvotes: 7

Views: 9846

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129344

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.

Upvotes: 10

Related Questions