Windows API Reference

Overview

The File I/O kernel APIs provide low‑level access to files, devices, pipes, and other I/O objects. These functions are part of the kernel32.dll library and are used for creating, reading, writing, and managing file handles.

Key Functions

Function Header Description Link
CreateFileW Windows.h Creates or opens a file or I/O device. Details
ReadFile Windows.h Reads data from a file or I/O device. Details
WriteFile Windows.h Writes data to a file or I/O device. Details
SetFilePointerEx Windows.h Moves the file pointer to a specified location. Details
GetFileSizeEx Windows.h Retrieves the size of a file. Details

Example: Reading a Text File

The following C++ example demonstrates how to open a file, read its contents, and close the handle using the kernel File I/O APIs.

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

int main() {
    HANDLE hFile = CreateFileW(
        L"example.txt",
        GENERIC_READ,
        FILE_SHARE_READ,
        nullptr,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        nullptr);

    if (hFile == INVALID_HANDLE_VALUE) {
        std::wcerr << L"Failed to open file. Error: " << GetLastError() << std::endl;
        return 1;
    }

    LARGE_INTEGER fileSize;
    if (!GetFileSizeEx(hFile, &fileSize)) {
        std::wcerr << L"Failed to get size. Error: " << GetLastError() << std::endl;
        CloseHandle(hFile);
        return 1;
    }

    DWORD bytesToRead = static_cast<DWORD>(fileSize.QuadPart);
    std::string buffer(bytesToRead, 0);

    DWORD bytesRead;
    if (!ReadFile(hFile, &buffer[0], bytesToRead, &bytesRead, nullptr)) {
        std::wcerr << L"Read failed. Error: " << GetLastError() << std::endl;
    } else {
        std::cout << buffer << std::endl;
    }

    CloseHandle(hFile);
    return 0;
}

Compile with cl /EHsc example.cpp and run the resulting executable.

Related Topics