[Windows API] Code to get file size » bits and bytes

[Windows API] Code to get file size » bits and bytes

In this blog post I’ll be demonstrating different API’s and techniques used to retrieve size of a file. I haven’t tested this much, you might want to add parameter integrity check etc., also probably better error checks. Use this code at your own risk.

  1. Using GetFileSizeEx
  2. Using _wstat64
  3. Using GetFileInformationByHandleEx
  4. Using FindFirstFileW
  5. Using fseek and ftell
Method 1: Using GetFileSizeEx

Here is a short code snippet to get size of a file using the Windows API GetFileSizeEx. Wrote this for a friend, so thought this will be useful for others as well.

Windows Store apps:  GetFileSizeEx is not supported. Use GetFileInformationByHandleEx.

__int64 PrvGetFileSize(const wchar_t* path)
{
    HANDLE hFile = ::CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Failed to open file: %S, error: %lu", path, GetLastError());
        return -1;
    }

    LARGE_INTEGER li = { 0 };
    if(GetFileSizeEx(hFile, &li) == 0)
    {
        printf("Failed to get file size: %lu", GetLastError());
        CloseHandle(hFile);
        return -1;
    }

    CloseHandle(hFile);

    return li.QuadPart;
}
Method 2: Using _wstat64

[Windows API] Code to get file size » bits and bytes

Appreciate your comments...