Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,569 questions

56,787 answers

573 users

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