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:
- Handles: File operations are performed using handles, which are opaque identifiers representing open files or other kernel objects.
- File Paths: Files and directories are identified by their paths, which can be absolute or relative.
- Streams: File I/O can be viewed as reading from or writing to a stream of bytes.
- Buffering: For performance, I/O operations are often buffered, meaning data is temporarily stored before being committed to disk or read from it.
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:
GetFileAttributes
: Retrieves attributes for a specified file or directory.SetFileAttributes
: Sets attributes for a specified file or directory.GetFileSizeEx
: Retrieves the size of a specified file.
Directory Operations
The API also supports operations on directories:
CreateDirectory
: Creates a new directory.RemoveDirectory
: Removes an existing empty directory.FindFirstFile
/FindNextFile
: Used to enumerate files and subdirectories within a directory.
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
.