MSDN – Windows File I/O

Table of Contents

Introduction

Windows File I/O provides a set of native APIs for working with files and devices. These functions allow you to create, read, write, and manipulate file handles with fine‑grained control over buffering, sharing, and security.

Basic Operations

The typical workflow involves:

  1. Opening a handle with CreateFile
  2. Reading or writing data using ReadFile / WriteFile
  3. Closing the handle with CloseHandle

Each function offers a rich set of flags. For a full reference, see the linked topics on the left.

Code Sample

Below is a simple C++ example that creates a file, writes a string, and reads it back.

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

int main() {
    const wchar_t* filename = L"example.txt";
    HANDLE hFile = CreateFileW(
        filename,
        GENERIC_READ | GENERIC_WRITE,
        0,
        nullptr,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        nullptr);
    if (hFile == INVALID_HANDLE_VALUE) {
        std::cerr << "CreateFile failed: " << GetLastError() << std::endl;
        return 1;
    }

    const char* data = "Hello, Windows File I/O!";
    DWORD written;
    WriteFile(hFile, data, (DWORD)strlen(data), &written, nullptr);

    SetFilePointer(hFile, 0, nullptr, FILE_BEGIN);

    char buffer[64] = {0};
    DWORD read;
    ReadFile(hFile, buffer, sizeof(buffer)-1, &read, nullptr);
    std::cout << "Read back: " << buffer << std::endl;

    CloseHandle(hFile);
    return 0;
}

Best Practices