Format Size in bytes to more human readable size.

21 05 2008

In several situation we’ve to convert bytes into more readable units such as KB’s or MB’s or in GB’s. For instance, you you want to display the file size of certain files, of course you can display in bytes. But it make more readable to user if its displayed in much higher units. So how can we convert bytes into more human readable size?

You can use the function – StrFormatByteSize(). See the following code snippet. In the code, the size of the executable file is read and converted to readable size.

#include "Shlwapi.h"
// Get the current filename.
GetModuleFileName( AfxGetInstanceHandle(),
                   MAX_PATH );

// Open the file.
CFile CurrentFile;
CurrentFile.Open( szFileName, CFile::modeRead );

// Get the file size.
DWORD FileSize = 0;
FileSize = GetFileSize( HANDLE(CurrentFile.m_hFile),
                        0 );

// Now format the size in bytes to readable string.
const int MAX_FILE_SIZE_BUFFER = 255;
StrFormatByteSize( FileSize,
                   MAX_FILE_SIZE_BUFFER );

// The szFileSize contains converted size.

For converting byte size in DWORD, you just call StrFormatByteSize(). But for converting size in LONGLONG value, you’ve to call the Unicode version – StrFormatByteSizeW() explicitly.

BTW, don’t forget to specify Shlwapi.lib to your project settings.

Targeted Audience – Beginners.