Vincent
Vincent

Reputation: 60381

Get file size with std::ios::ate?

Several topics (see Using C++ filestreams (fstream), how can you determine the size of a file? and C++: Getting incorrect file size) on how to measure a file size compute the difference between the beginning and the end of the file like that :

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;
    file.close();

    return fsize;
}

But instead of opening the file at the beginning, we can open it at the end and just take a measure, like that :

std::streampos fileSize( const char* filePath ){

    std::ifstream file( filePath, std::ios::ate | std::ios::binary );
    std::streampos fsize = file.tellg();
    file.close();

    return fsize;
}

Will it work ? And if not why ?

Upvotes: 1

Views: 7189

Answers (1)

Cornstalks
Cornstalks

Reputation: 38218

It should work just fine. The C++ standard says about std::ios::ate

ate - open and seek to end immediately after opening

There's no reason it would fail when a manual open-then-seek would succeed. And tellg is the same in either case.

Upvotes: 2

Related Questions