Get File Size with Kernel32 Api and Ntdll Api (Native Api)
#pragma comment(lib, "ntdll.lib")
#include <Windows.h>
#include <winternl.h>
#define FileStandardInformation 5
typedef struct _FILE_STANDARD_INFORMATION {
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;// file size
ULONG NumberOfLinks;
BOOLEAN DeletePending;
BOOLEAN Directory;
} FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION;
BOOL GetFileSizeNtdll(PCWSTR path, PLARGE_INTEGER pFSize)
{
UNICODE_STRING pathUniStr;
OBJECT_ATTRIBUTES obja;
IO_STATUS_BLOCK iost;
HANDLE hFile;
FILE_STANDARD_INFORMATION fileStInfo;
RtlDosPathNameToNtPathName_U(path, &pathUniStr, NULL, NULL);
InitializeObjectAttributes(&obja, &pathUniStr, OBJ_CASE_INSENSITIVE, NULL, NULL);
if (!NT_SUCCESS(NtCreateFile(&hFile, FILE_READ_ATTRIBUTES | SYNCHRONIZE, &obja, &iost, NULL, 0, 0, FILE_OPEN, 0, NULL, 0)))
return FALSE;
if (!NT_SUCCESS(NtQueryInformationFile(hFile, &iost, &fileStInfo, sizeof(fileStInfo), FileStandardInformation)))
return FALSE;
*pFSize = fileStInfo.EndOfFile;
NtClose(hFile);
}
BOOL GetFileSizeKernel32(PCWSTR path, PLARGE_INTEGER pFSize)
{
HANDLE hFile;
BOOL ret;
if ((hFile = CreateFileW(path, FILE_READ_ATTRIBUTES | SYNCHRONIZE, 0, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
return FALSE;
ret= GetFileSizeEx(hFile, pFSize);
CloseHandle(hFile);
return ret;
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
LARGE_INTEGER fSize1,fSize2;
//Method 1
GetFileSizeKernel32(L"C:\\Users\\la\\Desktop\\test.txt",&fSize1);
//Method 2
GetFileSizeNtdll(L"C:\\Users\\la\\Desktop\\test.txt", &fSize2);
return 0;
}
Please Vote this post if you like it.
Please Follow me if you like my posts.
If you have any questions about this post, ask in comments.
Follow me on :
DTube
Hive