Tag Archives: files

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.

#define __S_ISTYPE(mode, mask)  (((mode) & _S_IFMT) == (mask))
#define S_ISDIR(mode)    __S_ISTYPE((mode), _S_IFDIR)
Then, write next function:
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;
}

If you’re using WinAPI there is an even faster way in order to get file size.

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;
}

Finally, call these functions wherever you need.