Files and I/O Services
This section covers the Windows API functions and concepts related to file manipulation, input/output operations, and management of storage devices.
Core Concepts
Understanding file I/O in Windows involves concepts such as:
- File Handles and Objects
- Read/Write Operations
- File Attributes and Permissions
- Asynchronous I/O
- File Streams and Buffering
- Directory Management
Key Functions
The following are some of the most frequently used functions for file and I/O operations:
CreateFile: Creates or opens a file, disk, or communication resource.ReadFile: Reads data from a file or I/O device.WriteFile: Writes data to a file or I/O device.CloseHandle: Closes an open object handle.SetFilePointer: Moves the file pointer of the specified file.GetFileSizeEx: Retrieves the size of the specified file.CreateDirectory: Creates a directory.RemoveDirectory: Removes an existing directory.FindFirstFile/FindNextFile: Finds files that match a given path.
Advanced Topics
For more complex scenarios, consider exploring:
- Asynchronous I/O: Using
ReadFileExandWriteFileExwith I/O Completion Ports for high-performance applications. - Mapped Files: Using memory-mapped files for efficient data sharing and large file access.
- Volume Management: APIs for interacting with disk volumes and file systems.
- Device I/O Control (IOCTL): Sending custom commands to device drivers.
Example: Reading a File
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hFile;
char buffer[1024];
DWORD bytesRead;
hFile = CreateFile(
L"example.txt", // File name
GENERIC_READ, // Desired access
FILE_SHARE_READ, // Share mode
NULL, // Security attributes
OPEN_EXISTING, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL); // Template file
if (hFile == INVALID_HANDLE_VALUE) {
printf("Error opening file: %lu\n", GetLastError());
return 1;
}
if (ReadFile(hFile, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) {
buffer[bytesRead] = '\0'; // Null-terminate the string
printf("File content:\n%s\n", buffer);
} else {
printf("Error reading file: %lu\n", GetLastError());
}
CloseHandle(hFile);
return 0;
}