Files and I/O API Reference
This section covers the Windows API functions for managing files, directories, and performing input/output operations.
Core Concepts
Understanding the fundamental concepts behind file and I/O operations in Windows is crucial for effective programming. This includes:
- File Handles: Unique identifiers returned by the system when a file is opened.
- I/O Buffering: Strategies for managing data transfer between applications and storage devices.
- Asynchronous I/O: Techniques for performing I/O operations without blocking the calling thread.
- File Attributes and Permissions: Properties associated with files and directories, controlling access.
Key Functions
File Creation and Opening
Functions to create new files or open existing ones.
- CreateFile: Opens or creates a file or device.
- OpenFile: Opens an existing file.
File Reading and Writing
Functions for reading data from and writing data to files.
- ReadFile: Reads data from a file or I/O device.
- WriteFile: Writes data to a file or I/O device.
- ReadFileEx: Reads data from a file or device asynchronously.
- WriteFileEx: Writes data to a file or device asynchronously.
File Positioning
Functions to set and get the current file position.
- SetFilePointer: Moves or obtains the current read/write pointer of a file.
- GetFileSizeEx: Retrieves the size of a file.
File Closing and Management
Functions to close file handles and manage file information.
- CloseHandle: Closes an open object handle.
- FlushFileBuffers: Forces buffered data to be written to a specified file.
- GetFileInformationByHandle: Retrieves detailed information about a file.
Directory Operations
Functions for creating, deleting, and enumerating directories.
- CreateDirectory: Creates a directory.
- RemoveDirectory: Deletes an empty directory.
- FindFirstFile: Retrieves information about the first file or directory in a specified path.
- FindNextFile: Retrieves information about the next file or directory.
- FindClose: Closes a file search handle.
Common Data Structures
Essential structures used with file and I/O functions:
OVERLAPPED: Structure used for asynchronous I/O operations.WIN32_FIND_DATA: Structure containing information about a found file or directory.FILE_STANDARD_INFO: Structure containing standard file information.
Error Handling
Most I/O operations can fail. It's crucial to check the return values of API functions and use GetLastError to retrieve detailed error information.
DWORD errorCode = GetLastError();
if (errorCode != ERROR_SUCCESS) {
// Handle the error
LPTSTR errorMessage = NULL;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&errorMessage,
0,
NULL);
// Display or log errorMessage
LocalFree(errorMessage);
}