ドライブの空き容量を取得する (GetDiskFreeSpaceEx)

WinAPIを使用して接続されているドライブの情報を取得します。

たぶんWindows2000より前では動きません。

参考にしたページ

コード

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

int main(void)
{
    DWORD dwDrive;
    char pszDrive[16];
    UINT DriveType;
    BOOL fResult;
    unsigned __int64 i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
    char szVolume[256];
    DWORD dwSerial, dwLength, dwFlags;
    char szSystem[256];

    //ドライブレターを順番にチェック
    dwDrive = GetLogicalDrives();
    for (int nDrive = 0; nDrive < 26; nDrive++){

        //そのドライブレターが使用されているか
        if (dwDrive & (1 << nDrive)){
        
            sprintf_s(pszDrive, sizeof(pszDrive), "%c:\\", nDrive + 'A');

            //HDDかどうか
            DriveType = GetDriveTypeA(pszDrive);
            if (DriveType == DRIVE_FIXED || DriveType == DRIVE_REMOVABLE) {

                printf("%s\n", pszDrive);

                fResult = GetVolumeInformationA(pszDrive, szVolume, sizeof(szVolume), &dwSerial, &dwLength, &dwFlags, szSystem, sizeof(szSystem));
                if (fResult) {
                    printf("ボリューム名          :%s\n", szVolume);
                    printf("ボリュームのシリアル番号    :%08X\n", dwSerial);
                    printf("ファイル名の最大の長さ     :%lu\n", dwLength);
                    printf("ファイルシステムのオプション  :%08X\n", dwFlags);
                    printf("ファイルシステム名       :%s\n", szSystem);
                }
                else {
                    printf("エラー:%lu\n", GetLastError());
                }

                fResult = GetDiskFreeSpaceExA(pszDrive, (PULARGE_INTEGER)&i64FreeBytesToCaller, (PULARGE_INTEGER)&i64TotalBytes, (PULARGE_INTEGER)&i64FreeBytes);
                if (fResult) {
                    printf("呼び出し側が利用できるバイト数 :%I64u\n", i64FreeBytesToCaller);
                    printf("ディスク全体のバイト数     :%I64u\n", i64TotalBytes);
                    printf("ディスク全体の空きバイト数   :%I64u\n", i64FreeBytes);
                }
                else {
                    printf("エラー:%lu\n", GetLastError());
                }

                printf("\n");

            }
        }
    }

}