c++cportabilityfilesizeplatform-independent

Portable way to get file size in C/C++


I need to determin the byte size of a file.

The coding language is C++ and the code should work with Linux, windows and any other operating system. This implies using standard C or C++ functions/classes.

This trivial need has apparently no trivial solution.


Solution

  • Using std's stream you can use:

    std::ifstream ifile(....);
    ifile.seekg(0, std::ios_base::end);//seek to end
    //now get current position as length of file
    ifile.tellg();
    

    If you deal with write only file (std::ofstream), then methods are some another:

    ofile.seekp(0, std::ios_base::end);
    ofile.tellp();