How to get the size of a file using the Win32 API in C++

2 Answers

0 votes
#include <iostream>
#include <windows.h>

class Handle {
public:
    explicit Handle(HANDLE h) : h_(h) {}
    ~Handle() { if (h_ != INVALID_HANDLE_VALUE) CloseHandle(h_); }
    HANDLE get() const { return h_; }

private:
    HANDLE h_;
};

int main() {
    LPCWSTR fname = L"d:\\data.txt";

    Handle file(CreateFileW(
        fname,
        GENERIC_READ,
        FILE_SHARE_READ,
        nullptr,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        nullptr
    ));

    if (file.get() == INVALID_HANDLE_VALUE) {
        std::wcout << L"Could not open " << fname
            << L", error " << GetLastError() << L"\n";
        return 1;
    }

    DWORD size = GetFileSize(file.get(), nullptr);
    std::wcout << fname << L" size is " << size << L" bytes\n";

    return 0;
}



/*
run:

d:\data.txt size is 502 bytes

*/

 



answered Jan 30 by avibootz
0 votes
#include <iostream>
#include <windows.h>

void closeHandleIfValid(HANDLE h) {
    if (h != INVALID_HANDLE_VALUE) {
        CloseHandle(h);
    }
}

HANDLE openFileReadOnly(const wchar_t* fname) {
    return CreateFileW(
        fname,
        GENERIC_READ,
        FILE_SHARE_READ,
        nullptr,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        nullptr
    );
}

int main() {
    LPCWSTR fname = L"d:\\data.txt";

    HANDLE file = openFileReadOnly(fname);

    if (file == INVALID_HANDLE_VALUE) {
        std::wcout << L"Could not open " << fname
            << L", error " << GetLastError() << L"\n";
        return 1;
    }

    DWORD size = GetFileSize(file, nullptr);
    closeHandleIfValid(file);

    std::wcout << fname << L" size is " << size << L" bytes\n";

    return 0;
}




/*
run:

d:\data.txt size is 502 bytes

*/

 



answered Jan 30 by avibootz
...