Skip to content

Get File Size

A minimal C program that opens a file with CreateFile and prints its size in bytes using GetFileSize.

Published Apr 20, 2000

The shortest possible Win32 way to find out how big a file is: CreateFile for read access, then GetFileSize. Useful as the starting point when you need the raw handle-based approach rather than the C runtime's _stat/fseek tricks - for instance when you are already holding a handle or working with streams. Note the classic pitfall this snippet illustrates: check the return of CreateFile (or GetLastError) before trusting the size, since a failed open returns an invalid handle.

#include <Stdio.H>
#include <Stdlib.H>
#include <Windows.H>

int main()
{
	FILE *Source;
	int Result;
	DWORD xInt;

	Source = CreateFile("TestFile.Exe",GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
	Result = GetLastError();
	if(Result == ERROR_SUCCESS)
	{
		xInt = GetFileSize(Source,NULL);
		printf("FileSize = %d Bytes\n",xInt);
	}
	else{
		printf("ErrorCode %d\n",Result);
	}

	return 0;
}

For files larger than 4 GB, pass a LARGE_INTEGER* to the second parameter of GetFileSize instead of NULL.

An unhandled error has occurred. Reload 🗙