更快的方式获取文件大小信息C ++ [英] Faster way to get File Size information C++

查看:188
本文介绍了更快的方式获取文件大小信息C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来获取文件的FileSize。我在WinCE上运行这个。这是我目前的代码看起来特别慢的

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


推荐答案

我想使用这样的:

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



如果你使用的编译器支持它,你可能想使用 long long 而不是 __ int64 。您可能不会希望使用 int 虽然,因为这将只能正确工作的文件高达2千兆字节,并且大于那个文件现在很常见(虽然在WinCE设备上可能不是很常见)。

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).

我希望这比其他大多数方法更快。它不需要打开文件本身,只需找到文件的目录条目(或者像NTFS,它的主文件表条目)。

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).

这篇关于更快的方式获取文件大小信息C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆