c++filesizefstreamistream

Using C++ filestreams (fstream), how can you determine the size of a file?


I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream class from the fstream header?


Solution

  • You can seek until the end, then compute the difference:

    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;
    }