File Operations (Windows API)

Overview

The Windows File I/O API provides a set of functions for creating, reading, writing, and managing files at a low level. These functions are part of the kernel32.dll library and are available to both native C/C++ applications and other languages that can interoperate with the Win32 API.

Key Functions

CreateFile

Opens or creates a file or I/O device.

#include <windows.h>

HANDLE hFile = CreateFileW(
    L"C:\\Temp\\example.txt",          // lpFileName
    GENERIC_READ | GENERIC_WRITE,     // dwDesiredAccess
    0,                                // dwShareMode
    NULL,                             // lpSecurityAttributes
    CREATE_ALWAYS,                    // dwCreationDisposition
    FILE_ATTRIBUTE_NORMAL,            // dwFlagsAndAttributes
    NULL);                            // hTemplateFile

if (hFile == INVALID_HANDLE_VALUE) {
    // Handle error
}

ReadFile

Reads data from a file or input device.

#include <windows.h>

DWORD bytesRead;
CHAR buffer[256];
BOOL result = ReadFile(
    hFile,               // hFile
    buffer,              // lpBuffer
    sizeof(buffer)-1,    // nNumberOfBytesToRead
    &bytesRead,         // lpNumberOfBytesRead
    NULL);               // lpOverlapped

if (result) {
    buffer[bytesRead] = '\0';
    // Use buffer
}

WriteFile

Writes data to a file or output device.

#include <windows.h>

const CHAR* data = "Hello, Windows!";
DWORD bytesWritten;
BOOL result = WriteFile(
    hFile,               // hFile
    data,                // lpBuffer
    (DWORD)strlen(data), // nNumberOfBytesToWrite
    &bytesWritten,      // lpNumberOfBytesWritten
    NULL);               // lpOverlapped

if (!result) {
    // Handle error
}

CloseHandle

Closes an open object handle.

#include <windows.h>

CloseHandle(hFile);

DeleteFile

Deletes an existing file.

#include <windows.h>

BOOL result = DeleteFileW(L"C:\\Temp\\example.txt");
if (!result) {
    // Handle error
}

GetFileAttributes

Retrieves file attribute information.

#include <windows.h>

DWORD attrs = GetFileAttributesW(L"C:\\Temp\\example.txt");
if (attrs == INVALID_FILE_ATTRIBUTES) {
    // Handle error
}

SetFileAttributes

Sets file attribute information.

#include <windows.h>

BOOL result = SetFileAttributesW(
    L"C:\\Temp\\example.txt",
    FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY);

if (!result) {
    // Handle error
}

Best Practices