Silviu-Marius Ardelean's blog

a software engineer's web log

File size fast detection

Many times in our job, we need to work with files and need to know file properties.
One of the most important properties is file size. Of course, there are a lot of API that allows finding this property, but most of them needs additional file operations: open file, find file size and close file.

A direct and fast way in order to detect the file size without these operations means the CRT run-time library’s function _tstat64() and stuff.

In the header file or on .cpp file please add next macros definitions:
[cpp]
#define __S_ISTYPE(mode, mask) (((mode) & _S_IFMT) == (mask))
#define S_ISDIR(mode) __S_ISTYPE((mode), _S_IFDIR)
[/cpp]

Then, write next function:
[cpp]
long long GetFileSizeFast(const TCHAR *szFilePath)
{
if (!szFilePath || !szFilePath[0] || !PathFileExists(szFilePath))
return -1;

long long nSize = -1;
struct __stat64 buf;
nSize = (_tstat64( szFilePath, &buf ) == 0) ? buf.st_size : -1;
if (S_ISDIR(buf.st_mode)) nSize = -1;

return nSize;
}[/cpp]

If you’re using WinAPI there is an even faster way in order to get file size.
[cpp]long long GetFileSizeFastest(const TCHAR* szFilePath)
{
if (!szFilePath || !szFilePath[0] || !PathFileExists(szFilePath))
return -1;

WIN32_FIND_DATA sFileData;
HANDLE hFind = FindFirstFile(szFilePath, &sFileData);
if (hFind == INVALID_HANDLE_VALUE)
return -1;

FindClose(hFind);

return (sFileData.nFileSizeHigh * (MAXDWORD+1LL)) + sFileData.nFileSizeLow;
}[/cpp]

Finally, call these functions wherever you need.

, , , , , , ,
23/11/2010 at 10:52 PM Comments (22)