且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不使用C ++打开文件的情况下检查文件大小?

更新时间:2023-02-08 12:19:13

您应致电 GetFileSizeEx ,它比旧版 GetFileSize 。您需要通过调用 CreateFile 来打开文件,但这是一个便宜的操作。您假设打开一个文件甚至是12GB的文件都非常昂贵,这是错误的。

You should call GetFileSizeEx which is easier to use than the older GetFileSize. You will need to open the file by calling CreateFile but that's a cheap operation. Your assumption that opening a file is expensive, even a 12GB file, is false.

您可以使用以下函数来完成工作:

You could use the following function to get the job done:

__int64 FileSize(const wchar_t* name)
{
    HANDLE hFile = CreateFile(name, GENERIC_READ, 
        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 
        FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile==INVALID_HANDLE_VALUE)
        return -1; // error condition, could call GetLastError to find out more

    LARGE_INTEGER size;
    if (!GetFileSizeEx(hFile, &size))
    {
        CloseHandle(hFile);
        return -1; // error condition, could call GetLastError to find out more
    }

    CloseHandle(hFile);
    return size.QuadPart;
}

还有其他API调用可以返回文件大小而不会强迫您创建文件句柄,尤其是 GetFileAttributesEx 。但是,此功能只是在后台打开文件是完全合理的。

There are other API calls that will return you the file size without forcing you to create a file handle, notably GetFileAttributesEx. However, it's perfectly plausible that this function will just open the file behind the scenes.

__int64 FileSize(const wchar_t* name)
{
    WIN32_FILE_ATTRIBUTE_DATA fad;
    if (!GetFileAttributesEx(name, GetFileExInfoStandard, &fad))
        return -1; // error condition, could call GetLastError to find out more
    LARGE_INTEGER size;
    size.HighPart = fad.nFileSizeHigh;
    size.LowPart = fad.nFileSizeLow;
    return size.QuadPart;
}

如果您使用Visual Studio进行编译,并且希望避免调用Win32 API,那么您可以使用 _wstat64

If you are compiling with Visual Studio and want to avoid calling Win32 APIs then you can use _wstat64.

以下是该功能的 _wstat64 版:

__int64 FileSize(const wchar_t* name)
{
    __stat64 buf;
    if (_wstat64(name, &buf) != 0)
        return -1; // error, could use errno to find out more

    return buf.st_size;
} 






如果性能曾经成为问题,那么您应该在目标平台上确定各种选择的时间,以便做出决定。不要以为不需要您调用 CreateFile 的API会更快。它们可能是,但您要等到定时后才能知道。


If performance ever became an issue for you then you should time the various options on all the platforms that you target in order to reach a decision. Don't assume that the APIs that don't require you to call CreateFile will be faster. They might be but you won't know until you have timed it.