File System API Reference

Introduction

The Windows File System API provides functions and structures for creating, reading, writing, and managing files and directories. It includes legacy Win32 functions, modern CopyFile2, and the Windows.Storage namespace for UWP apps.

Key Functions

CreateFileW

Creates or opens a file or device for read/write access.

#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

ReadFile

Reads data from the specified file or input/output (I/O) device.

#include <windows.h>

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

WriteFile

Writes data to the specified file or I/O device.

#include <windows.h>

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

DeleteFileW

Deletes an existing file.

#include <windows.h>

BOOL result = DeleteFileW(L"C:\\temp\\example.txt");

Important Structures

  • WIN32_FIND_DATAW – Retrieves file attribute data.
  • FILETIME – Represents the number of 100‑nanosecond intervals since January 1, 1601 (UTC).
  • OVERLAPPED – Used for asynchronous (overlapped) I/O operations.

Complete Example: List Files in a Directory

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

int main() {
    WIN32_FIND_DATAW ffd;
    HANDLE hFind = FindFirstFileW(L"C:\\temp\\*", &ffd);
    if (hFind == INVALID_HANDLE_VALUE) {
        wprintf(L"FindFirstFile failed (error %lu)\\n", GetLastError());
        return 1;
    }

    do {
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            wprintf(L"[DIR] %s\\n", ffd.cFileName);
        else
            wprintf(L"      %s\\n", ffd.cFileName);
    } while (FindNextFileW(hFind, &ffd) != 0);

    FindClose(hFind);
    return 0;
}