I am using
if( !GetDiskFreeSpaceEx(
lpDirectoryName, // directory name
&m_uliFreeBytesAvailable, // bytes available to caller
&m_uliTotalNumberOfBytes, // bytes on disk
&m_uliTotalNumberOfFreeBytes) ) // free bytes on disk
return false;
else
diskFreeSpaceInKB = static_cast<long int>(m_uliTotalNumberOfFreeBytes.QuadPart/ONE_KB_IN_BYTES) ;
That returns negative value for disk that have a capacity greater than 1TB.
I need the accurate value representing the available disk space so that the user can record a movie if there is enough space on that disk.
I see you typed diskFreeSpaceInKB = static_cast<long int>...
, so I assume that diskFreeSpaceInKB
is a long int
variable.
First, let's have a look on the GetDiskFreeSpaceEx
prototype.
BOOL WINAPI GetDiskFreeSpaceEx(
_In_opt_ LPCTSTR lpDirectoryName,
_Out_opt_ PULARGE_INTEGER lpFreeBytesAvailable,
_Out_opt_ PULARGE_INTEGER lpTotalNumberOfBytes,
_Out_opt_ PULARGE_INTEGER lpTotalNumberOfFreeBytes
);
PULARGE_INTEGER
= Pointer to ULARGE_INTEGER
ULARGE_INTERGER = An union that stores a 64-bit unsigned integer
Now let's see what you did.
diskFreeSpaceInKB = static_cast<long int>(m_uliTotalNumberOfFreeBytes.QuadPart/ONE_KB_IN_BYTES)
In Windows, int
/long
/long int
are always signed 32-bit
regardless you're compiling 32-bit or 64-bit build because Windows uses LLP64 model. So basically you're casting a unsigned 64-bit integer
divided by ONE_KB_IN_BYTES
to a signed 32-bit integer
.
So why I get negative number?
Because the value exceeds the maximum positive value of the signed data type.
How to fix it?
Declare diskFreeSpaceInKB
as UINT64
, and static_cast<UINT64>
.