Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

c - Conversion from GB to DWORD or vice-versa

I want to compare a filesize to check if it is below 8GB. How could I convert either the filseSize( which is in DWORD) to GB or the 8 GB to DWORD?

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm guessing from your DWORD hint, you are on the Windows platform and using Win32 APIs to get file sizes.

Don't call GetFileSize. It's limited to a DWORD (32-bit), which I think it what your question is about.

Instead, invoke GetFileSizeEx, which gives you back a 64-bit result for a file handle. Or GetFileAttributesEx which gives back a struct with a 64-bit size in it split across two dwords.

Example:

const LONGLONG MAX_FILE_SIZE = 1024LL * 1024LL * 1024LL * 8;
LARGE_INTEGER li = {0};
if (GetFileSizeEx(hFile, &li)) {
    LONGLONG filesize = li.QuadPart;
    if (filesize > MAX_FILE_SIZE) {
        ...
    }
}

OR

const LONGLONG MAX_FILE_SIZE = 1024LL * 1024LL * 1024LL * 8;
WIN32_FILE_ATTRIBUTE_DATA info = {0};
if (GetFileAttributesEx(filename, GetFileExInfoStandard, (void*)&info)) {
    LONGLONG filesize = info.nFileSizeHigh;
    filesize  = filesize << 32;
    filesize |= info.nFileSizeLow;
    if (filesize > MAX_FILE_SIZE) {
        ...
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...