Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does seekg find the end of the file?

Tags:

c++

fstream

seekg

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.

like image 902
Lakey Avatar asked Feb 10 '13 00:02

Lakey


1 Answers

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.

like image 159
Mats Petersson Avatar answered Oct 05 '22 11:10

Mats Petersson