File I/O

The Windows API provides a rich set of functions for managing files and directories, allowing applications to create, read, write, delete, and query information about file system objects.

Key Concepts

Understanding the core concepts of Windows file I/O is crucial for effective development:

Core Functions

Creating and Opening Files

The primary function for creating or opening files is CreateFile. This versatile function can create new files, open existing ones, or open files with specific access rights and sharing modes.

HANDLE CreateFile(
  LPCSTR lpFileName,              // File name
  DWORD dwDesiredAccess,          // Desired access level
  DWORD dwShareMode,              // Sharing mode
  LPSECURITY_ATTRIBUTES lpSecurityAttributes, // Security attributes
  DWORD dwCreationDisposition,    // How to create or open
  DWORD dwFlagsAndAttributes,     // File attributes
  HANDLE hTemplateFile            // Handle to template file
);

Reading from Files

Use the ReadFile function to read data from an open file handle.

BOOL ReadFile(
  HANDLE       hFile,              // Handle to file
  LPVOID       lpBuffer,           // Buffer to receive data
  DWORD        nNumberOfBytesToRead, // Bytes to read
  LPDWORD      lpNumberOfBytesRead,  // Bytes actually read
  LPOVERLAPPED lpOverlapped        // Overlapped structure
);

Writing to Files

The WriteFile function writes data to an open file handle.

BOOL WriteFile(
  HANDLE       hFile,              // Handle to file
  LPCVOID      lpBuffer,           // Buffer containing data to write
  DWORD        nNumberOfBytesToWrite, // Bytes to write
  LPDWORD      lpNumberOfBytesWritten, // Bytes actually written
  LPOVERLAPPED lpOverlapped        // Overlapped structure
);

Closing Files

Always close file handles when they are no longer needed to release system resources using CloseHandle.

BOOL CloseHandle(
  HANDLE hObject // Handle to object
);

File Attributes and Information

You can retrieve and set various attributes and information about files and directories:

Directory Operations

The API also supports operations on directories:

Asynchronous I/O

For improved performance and responsiveness, especially in applications with graphical interfaces, asynchronous I/O can be employed using the OVERLAPPED structure with functions like ReadFileEx and WriteFileEx.

Note: For low-level access to file system structures, consider using the File System API functions.