#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
*/