Search code examples
c++windowsboostdiskspaceboost-filesystem

boost::filesystem::space() is reporting wrong diskspace


I have 430 GB free on drive C:. But for this program:

#include <iostream>
#include <boost/filesystem.hpp>

int main()
{
    boost::filesystem::path p("C:");

    std::size_t freeSpace = boost::filesystem::space(p).free;
    std::cout<<freeSpace << " Bytes" <<std::endl;
    std::cout<<freeSpace / (1 << 20) << " MB"<<std::endl;

    std::size_t availableSpace = boost::filesystem::space(p).available;
    std::cout << availableSpace << " Bytes" <<std::endl;
    std::cout << availableSpace / (1 << 20) << " MB"<<std::endl;

    std::size_t totalSpace = boost::filesystem::space(p).capacity;
    std::cout << totalSpace << " Bytes" <<std::endl;
    std::cout << totalSpace / (1 << 20) << " MB"<<std::endl;

    return 0;
}

The output is:

2542768128 Bytes
2424 MB
2542768128 Bytes
2424 MB
2830102528 Bytes
2698 MB

I need to know how much diskspace is available because my application has to download a huge file, and I need to know whether it's viable to download it.

I'm using mingw on Windows:

g++ (i686-posix-dwarf-rev2, Built by MinGW-W64 project) 7.1.0

I also tried using MXE to cross compile from Linux:

i686-w64-mingw32.static-g++ (GCC) 5.5.0

Both are returning the same numbers.


Solution

  • std::size_t is not guaranteed to be the biggest standard unsigned type. Actually, it rarely is.

    And boost::filesystem defines space_info thus:

    struct space_info  // returned by space function
    {
      uintmax_t capacity;
      uintmax_t free; 
      uintmax_t available; // free space available to a non-privileged process
    };
    

    You would have easily avoided the error by using auto, which would be natural as the exact type is not of any importance. Nearly always only mismatch hurts, thus Almost Always auto.