Search code examples
c++optimizationwindows-ce

Faster way to get File Size information C++


I have a function to get a FileSize of a file. I am running this on WinCE. Here is my current code which seems particularily slow

int Directory::GetFileSize(const std::string &filepath)
{
    int filesize = -1;

#ifdef linux
    struct stat fileStats;
    if(stat(filepath.c_str(), &fileStats) != -1)
      filesize = fileStats.st_size;
#else
    std::wstring widePath;
    Unicode::AnsiToUnicode(widePath, filepath);

    HANDLE hFile = CreateFile(widePath.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (hFile > 0)
    {
      filesize = ::GetFileSize( hFile, NULL); 
    }

    CloseHandle(hFile);
#endif

    return filesize;
}

Solution

  • At least for Windows, I think I'd use something like this:

    __int64 Directory::GetFileSize(std::wstring const &path) { 
    
        WIN32_FIND_DATAW data;
        HANDLE h = FindFirstFileW(path.c_str(), &data);
        if (h == INVALID_HANDLE_VALUE)
            return -1;
    
        FindClose(h);
    
        return data.nFileSizeLow | (__int64)data.nFileSizeHigh << 32;
    }
    

    If the compiler you're using supports it, you might want to use long long instead of __int64. You probably do not want to use int though, as that will only work correctly for files up to 2 gigabytes, and files larger than that are now pretty common (though perhaps not so common on a WinCE device).

    I'd expect this to be faster than most other methods though. It doesn't require opening the file itself at all, just finding the file's directory entry (or, in the case of something like NTFS, its master file table entry).