Windows API – File API

Overview

The File API provides a set of functions for creating, opening, reading, writing, and managing files and directories on Windows operating systems. These functions are part of the Win32 API and are available to native C/C++ applications as well as to other languages via interop.

Key Functions

FunctionDescription
CreateFileCreates or opens a file, device, pipe, or console.
ReadFileReads data from a file or input device.
WriteFileWrites data to a file or output device.
CloseHandleCloses an open object handle.
GetFileAttributesRetrieves file or directory attributes.
SetFilePointerMoves the file pointer to a new location.
GetFileInformationByHandleRetrieves information about a file via its handle.

Enumerations & Constants

Common constants used with the File API include:

#define GENERIC_READ            (0x80000000L)
#define GENERIC_WRITE           (0x40000000L)
#define FILE_ATTRIBUTE_NORMAL   0x00000080
#define OPEN_EXISTING           3
#define CREATE_NEW              1
#define CREATE_ALWAYS           2
#define TRUNCATE_EXISTING       5
// ... many more

Code Sample – Reading a Text File

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

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::cerr << "Failed to open file. Error: " << GetLastError() << std::endl;
        return 1;
    }
    DWORD bytesRead;
    char buffer[256];
    if (!ReadFile(hFile, buffer, sizeof(buffer)-1, &bytesRead, nullptr)) {
        std::cerr << "Read failed. Error: " << GetLastError() << std::endl;
        CloseHandle(hFile);
        return 1;
    }
    buffer[bytesRead] = '\0';
    std::cout << "File contents: " << buffer << std::endl;
    CloseHandle(hFile);
    return 0;
}