Search code examples
cwindowswinapidiskspacefilesize

Programatically determining file "size on disk" in advance


I need to know how big a given in-memory buffer will be as an on-disk (usb stick) file before I write it. I know that unless the size falls on the block size boundary, its likely to get rounded up, e.g. a 1 byte file takes up 4096 bytes on-disk. I'm currently doing this using GetDiskFreeSpace() to work out the disk block size, then using this to calculate the on-disk size like this:

GetDiskFreeSpace(szDrive, &dwSectorsPerCluster, 
                 &dwBytesPerSector, NULL, NULL);

dwBlockSize = dwSectorsPerCuster * dwBytesPerSector;

if (dwInMemorySize % dwBlockSize != 0)
{
    dwSizeOnDisk = ((dwInMemorySize / dwBlockSize) * dwBlockSize) + dwBlockSize;
}
else
{
    dwSizeOnDisk = dwInMemorySize;
}

Which seems to work fine, BUT GetDiskFreeSpace() only works on disks up to 2GB according to MSDN. GetDiskFreeSpaceEx() doesn't return the same information, so my question is, how else can I calculate this information for drives >2GB? Is there an API call I've missed? Can I assume some hard values depending on the overall disk size?


Solution

  • MSDN only states that the GetDiskFreeSpace() function cannot report volume sizes greater than 2GB. It works fine for retrieving sectors per cluster and bytes per sector, I've used it myself for very similar-looking code ;-)

    But if you want disk capacity too, you'll need an additional call to GetDiskFreeSpaceEx().