GetDiskFreeSpace函数返回ERROR_INVALID_FUNCTION

时间:2015-07-28 17:55:44

标签: c winapi

我有以下代码,它应该获得外部驱动器的句柄并获得扇区大小。

HANDLE hRawDisk = CreateFile(L"\\\\.\\F:",
                             GENERIC_READ,
                             FILE_SHARE_READ | FILE_SHARE_WRITE, 
                             NULL,
                             OPEN_EXISTING, 
                             FILE_FLAG_NO_BUFFERING, 
                             NULL);

if (hRawDisk == INVALID_HANDLE_VALUE)
{
    printf("CreateFile failed\r\n");
    PrintLastError();
    return -1;
}

DWORD sectorsPerCluster;
DWORD bytesPerSector;
DWORD numberOfFreeClusters;
DWORD totalNumberOfClusters;

if (!GetDiskFreeSpace(L"\\\\.\\F:", &sectorsPerCluster, &bytesPerSector,
    &numberOfFreeClusters, &totalNumberOfClusters))
{
    printf("GetDiskFreeSpace failed\r\n");
    PrintLastError();
    CloseHandle(hRawDisk);
    return -2;
}

我不知道为什么函数GetDiskFreeSpace返回ERROR_INVALID_FUNCTION。是否有可能与访问权限有关?

使用GetDiskFreeSpaceEx函数可以得到完全相同的结果。

2 个答案:

答案 0 :(得分:2)

引用函数GetDiskFreeSpace的MSDN文档,关于第一个参数(https://msdn.microsoft.com/en-us/library/windows/desktop/aa364935(v=vs.85).aspx):

  

要获取其信息的磁盘的根目录   回。如果此参数为NULL,则该函数使用的根   当前的磁盘。如果此参数是UNC名称,则必须包含a   尾部反斜杠(例如," \ MyServer \ MyShare \")。的此外,   驱动器规范必须具有尾部反斜杠(例如,   " C:\")。调用应用程序必须具有FILE_LIST_DIRECTORY访问权限   该目录的权利。

因此,例如,您可以通过以下方式调用该函数:

GetDiskFreeSpace(L"F:\\", &sectorsPerCluster, &bytesPerSector,
    &numberOfFreeClusters, &totalNumberOfClusters)

答案 1 :(得分:0)

样品:

    auto path = _T("C:\\");
    ULARGE_INTEGER FreeBytesAvailable = { 0 };
    ULARGE_INTEGER TotalNumberOfBytes={ 0 };
    ULARGE_INTEGER TotalNumberOfFreeBytes={ 0 };

    BOOL ok = GetDiskFreeSpaceEx(
        path,
        &FreeBytesAvailable,
        &TotalNumberOfBytes,
        &TotalNumberOfFreeBytes
        );

    if (ok)
    {
        unsigned long long freeAvail = FreeBytesAvailable.QuadPart;
        unsigned long long total = TotalNumberOfBytes.QuadPart;
        unsigned long long totalfree = TotalNumberOfFreeBytes.QuadPart;

        TRACE("\nfree for user: MB: %lld; Total for user: MB: %lld, Free total MB:%lld \n", freeAvail /1024/1024, total / 1024 / 1024, totalfree / 1024 / 1024);


/// if eventually using MFC:
    CString s;
    s.Format(_T("free for user: MB: %lld; Total for user: MB: %lld, Free total MB:%lld \n"), freeAvail / 1024 / 1024, total / 1024 / 1024, totalfree / 1024 / 1024);