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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to use the Win32 API ReadFile function to read data from a file in C++

2 Answers

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

class WinHandle {
public:
    explicit WinHandle(HANDLE h) : handle(h) {}
    ~WinHandle() {
        if (handle != INVALID_HANDLE_VALUE) {
            CloseHandle(handle);
        }
    }

    HANDLE get() const { return handle; }

private:
    HANDLE handle;
};

int main() {
    try {
        WinHandle file(CreateFileA(
            "data.txt",
            GENERIC_READ,
            FILE_SHARE_READ,
            nullptr,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            nullptr
        ));

        if (file.get() == INVALID_HANDLE_VALUE) {
            throw std::runtime_error("Failed to open file. Error code: " +
                std::to_string(GetLastError()));
        }

        std::string buffer;
        buffer.resize(1024);

        DWORD bytesRead = 0;
        BOOL ok = ReadFile(
            file.get(),
            buffer.data(),
            static_cast<DWORD>(buffer.size() - 1),
            &bytesRead,
            nullptr
        );

        if (!ok) {
            throw std::runtime_error("Failed to read file. Error code: " +
                std::to_string(GetLastError()));
        }

        buffer.resize(bytesRead); // shrink to actual size

        std::cout << "Read " << bytesRead << " bytes from file:\n";
        std::cout << buffer << "\n";
    }
    catch (const std::exception& ex) {
        std::cerr << ex.what() << "\n";
        return 1;
    }

    return 0;
}




/*
run:

Read 13 bytes from file:
abcd
efg
hi

*/

 



answered Jan 25 by avibootz
0 votes
#include <windows.h>
#include <iostream>
#include <string>
#include <stdexcept>

HANDLE openFile(const char* filename) {
    HANDLE file = CreateFileA(
        filename,
        GENERIC_READ,
        FILE_SHARE_READ,
        nullptr,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        nullptr
    );

    if (file == INVALID_HANDLE_VALUE) {
        throw std::runtime_error(
            "Failed to open file. Error code: " +
            std::to_string(GetLastError())
        );
    }

    return file;
}

std::string readFile(HANDLE file) {
    std::string buffer(1024, '\0');
    DWORD bytesRead = 0;

    BOOL ok = ReadFile(
        file,
        buffer.data(),
        static_cast<DWORD>(buffer.size() - 1),
        &bytesRead,
        nullptr
    );

    if (!ok) {
        throw std::runtime_error(
            "Failed to read file. Error code: " +
            std::to_string(GetLastError())
        );
    }

    buffer.resize(bytesRead);

    return buffer;
}

void printFile(const std::string& data) {
    std::cout << "Read " << data.size() << " bytes from file:\n";
    std::cout << data << "\n";
}

int main() {
    HANDLE file = INVALID_HANDLE_VALUE;

    try {
        file = openFile("data.txt");

        // RAII cleanup using a local guard struct
        struct HandleGuard {
            HANDLE h;
            ~HandleGuard() { if (h != INVALID_HANDLE_VALUE) CloseHandle(h); }
        } guard{ file };

        std::string data = readFile(file);
        printFile(data);
    }
    catch (const std::exception& ex) {
        std::cerr << ex.what() << "\n";
        return 1;
    }

    return 0;
}




/*
run:

Read 13 bytes from file:
abcd
efg
hi

*/

 



answered Jan 25 by avibootz
edited Jan 25 by avibootz
...