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:

Advanced Topics

For more complex scenarios, consider exploring:

  • Asynchronous I/O: Using ReadFileEx and WriteFileEx with 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;
}
                

See Also