Reputation: 27
I tried to get file size for 16 GB txt file. but I got different size with real size. who can help me?
HANDLE FileHandle = INVALID_HANDLE_VALUE;
long long FileSize;
FileHandle = CreateFileA(szInputFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if(FileHandle == INVALID_HANDLE_VALUE)
return;
FileSize = GetFileSize(FileHandle, NULL);
Upvotes: 1
Views: 578
Reputation: 598134
If you don't really need an open HANDLE
to the actual file itself, you can instead use FindFirstFile()
or GetFileAttributesEx()
to query the file size from the filesystem, eg:
WIN32_FIND_DATA fd;
HANDLE FindHandle = FindFirstFile(szInputFileName, &fd);
if (FindHandle == INVALID_HANDLE_VALUE)
return;
FindClose(FindHandle);
ULONGLONG FileSize = (static_cast<ULONGLONG>(fd.nFileSizeHigh) << 32) + fd.nFileSizeLow;
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesEx(szInputFileName, GetFileExInfoStandard, &fad))
return;
ULONGLONG FileSize = (static_cast<ULONGLONG>(fad.nFileSizeHigh) << 32) + fad.nFileSizeLow;
Upvotes: 2
Reputation: 29287
As you can see in the GetFileSize
documentation:
If the file size exceeds 32bit, you must provide the 2nd argument, to be filled with the 32 high bits of the size.
Then you can combine the 2 in order to get the final file size.
Code example:
HANDLE FileHandle = INVALID_HANDLE_VALUE;
// ... (initialize FileHandle)
DWORD FileSizeLow;
DWORD FileSizeHigh;
//------------------------------------vvvvvvvvvvvvvv-
FileSizeLow = GetFileSize(FileHandle, &FileSizeHigh);
// Handle error case (see documentation link above) ...
uint64_t FileSize = ((uint64_t)FileSizeHigh << 32) + FileSizeLow;
// ...
Alternatively, as @IInspectable commented, you can use GetFileSizeEx
:
LARGE_INTEGER FileSizeL;
if (GetFileSizeEx(FileHandle, &FileSizeL))
{
LONGLONG FileSize = FileSizeL.QuadPart; // 64bit signed
// ...
}
else
{
// Handle error ...
}
Note: Using GetFileSizeEx
is actually the recomended way (the documentation above mentions it explicitly) thanks to a 64bit single result and easier error handling.
Upvotes: 7
Reputation: 36578
The GetFileSize
documentation recommends using GetFileSizeEx
instead which is simpler:
LARGE_INTEGER FileSize;
if (!GetFileSizeEx(FileHandle, &FileSize))
{
std::cout << "error getting file size\n";
}
else
{
std::cout << "file size: " << FileSize.QuadPart << "\n";
}
for a more c++ solution std::filesystem::file_size
(though this only works with a path, not a handle):
auto FileSize = std::filesystem::file_size(szInputFileName)
Upvotes: 4