How to get the total disk size using the Win32 API in C

1 Answer

0 votes
#include <windows.h>
#include <stdio.h>

int main(void)
{
    LPCWSTR rootPath = L"C:\\";

    ULARGE_INTEGER freeBytesAvailable;
    ULARGE_INTEGER totalBytes;
    ULARGE_INTEGER totalFreeBytes;

    BOOL ok = GetDiskFreeSpaceExW(
        rootPath,
        &freeBytesAvailable,   // free space available to the caller
        &totalBytes,           // total size of the disk
        &totalFreeBytes        // total free space on the disk
    );

    if (!ok) {
        printf("Error: %lu\n", GetLastError());
        return 1;
    }

    double totalGB = (double)totalBytes.QuadPart / (1024.0 * 1024.0 * 1024.0);
    double freeGB = (double)totalFreeBytes.QuadPart / (1024.0 * 1024.0 * 1024.0);

    wprintf(L"Disk: %s\n", rootPath);
    wprintf(L"Total size: %llu bytes (%.2f GB)\n", totalBytes.QuadPart, totalGB);
    wprintf(L"Free space: %llu bytes (%.2f GB)\n", totalFreeBytes.QuadPart, freeGB);

    return 0;
}



/*
run:

Disk: C:\
Total size: 999559262208 bytes (930.91 GB)
Free space: 284329418752 bytes (264.80 GB)

*/

 



answered Jan 30 by avibootz
...