MSDN Documentation – Windows APIs

Overview

The File I/O (Input/Output) API provides a set of functions for creating, reading, writing, and managing files and directories on Windows operating systems. These functions allow developers to interact with the file system directly, handling data streams, file attributes, security descriptors, and asynchronous operations.

Core Functions

FunctionPurposeHeader
CreateFileOpens or creates a file or I/O device.Windows.h
ReadFileReads data from a file or device.Windows.h
WriteFileWrites data to a file or device.Windows.h
CloseHandleCloses an open object handle.Windows.h
SetFilePointerMoves the file pointer.Windows.h
GetFileSizeExRetrieves the size of a file.Windows.h
DeleteFileDeletes an existing file.Windows.h
CopyFileCopies an existing file to a new file.Windows.h
MoveFileExMoves or renames a file.Windows.h
GetFileAttributesRetrieves file attributes.Windows.h

Sample Code – Reading a Text File

#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hFile = CreateFile(
        L"example.txt",                 // file name
        GENERIC_READ,                    // open for reading
        FILE_SHARE_READ,                 // share for reading
        NULL,                            // default security
        OPEN_EXISTING,                   // open existing file
        FILE_ATTRIBUTE_NORMAL,           // normal file
        NULL);                           // no template

    if (hFile == INVALID_HANDLE_VALUE) {
        wprintf(L"Failed to open file (error %lu)\n", GetLastError());
        return 1;
    }

    DWORD fileSize = 0;
    LARGE_INTEGER size;
    if (!GetFileSizeEx(hFile, &size)) {
        wprintf(L"Failed to get size (error %lu)\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }
    fileSize = (DWORD)size.QuadPart;

    char *buffer = (char*)malloc(fileSize + 1);
    if (!buffer) {
        wprintf(L"Memory allocation failed\n");
        CloseHandle(hFile);
        return 1;
    }

    DWORD bytesRead;
    if (!ReadFile(hFile, buffer, fileSize, &bytesRead, NULL) || bytesRead != fileSize) {
        wprintf(L"Read error (error %lu)\n", GetLastError());
        free(buffer);
        CloseHandle(hFile);
        return 1;
    }
    buffer[bytesRead] = '\0';   // Null‑terminate

    printf("File contents:\\n%s\\n", buffer);

    free(buffer);
    CloseHandle(hFile);
    return 0;
}