File I/O (Input/Output)
This section covers the Windows API functions and concepts related to file input and output operations. Efficiently reading from and writing to files is crucial for many applications.
Core Concepts
- File Handles: Unique identifiers returned by the system when a file is opened.
- File Pointers: A position within a file that indicates where the next read or write operation will begin.
- Buffering: Techniques used to improve the performance of I/O operations by temporarily storing data.
- Synchronization: Mechanisms to ensure that multiple threads or processes access files in a controlled manner.
Key API Functions
The following table lists some of the most commonly used functions for file I/O:
| Function Name | Description | Header File |
|---|---|---|
CreateFile |
Creates or opens a file or I/O device. | windows.h |
ReadFile |
Reads data from a file or I/O device. | windows.h |
WriteFile |
Writes data to a file or I/O device. | windows.h |
CloseHandle |
Closes an open object handle. | windows.h |
SetFilePointerEx |
Moves the file pointer of the specified file. | windows.h |
GetFileSizeEx |
Retrieves the size of the specified file. | windows.h |
FlushFileBuffers |
Forces the contents of the file buffers to be written to disk. | windows.h |
Example: Reading from a File
Here's a simple C++ example demonstrating how to read the contents of a text file:
#include <windows.h>
#include <iostream>
#include <vector>
int main() {
HANDLE hFile = CreateFile(
L"example.txt", // File name
GENERIC_READ, // Access mode
0, // Share mode
NULL, // Security attributes
OPEN_EXISTING, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL // Template file
);
if (hFile == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to open file. Error: " << GetLastError() << std::endl;
return 1;
}
BY_HANDLE_FILE_INFORMATION fileInfo;
if (!GetFileInformationByHandle(hFile, &fileInfo)) {
std::cerr << "Failed to get file info. Error: " << GetLastError() << std::endl;
CloseHandle(hFile);
return 1;
}
DWORD fileSize = fileInfo.nFileSizeLow;
if (fileSize == 0) {
std::cout << "File is empty." << std::endl;
CloseHandle(hFile);
return 0;
}
std::vector<char> buffer(fileSize);
DWORD bytesRead;
if (!ReadFile(hFile, buffer.data(), fileSize, &bytesRead, NULL)) {
std::cerr << "Failed to read from file. Error: " << GetLastError() << std::endl;
CloseHandle(hFile);
return 1;
}
std::cout.write(buffer.data(), bytesRead);
std::cout << std::endl;
CloseHandle(hFile);
return 0;
}