Table of Contents
Introduction
Windows File I/O provides a set of native APIs for working with files and devices. These functions allow you to create, read, write, and manipulate file handles with fine‑grained control over buffering, sharing, and security.
Basic Operations
The typical workflow involves:
- Opening a handle with
CreateFile
- Reading or writing data using
ReadFile
/WriteFile
- Closing the handle with
CloseHandle
Each function offers a rich set of flags. For a full reference, see the linked topics on the left.
Code Sample
Below is a simple C++ example that creates a file, writes a string, and reads it back.
#include <windows.h>
#include <string>
#include <iostream>
int main() {
const wchar_t* filename = L"example.txt";
HANDLE hFile = CreateFileW(
filename,
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
std::cerr << "CreateFile failed: " << GetLastError() << std::endl;
return 1;
}
const char* data = "Hello, Windows File I/O!";
DWORD written;
WriteFile(hFile, data, (DWORD)strlen(data), &written, nullptr);
SetFilePointer(hFile, 0, nullptr, FILE_BEGIN);
char buffer[64] = {0};
DWORD read;
ReadFile(hFile, buffer, sizeof(buffer)-1, &read, nullptr);
std::cout << "Read back: " << buffer << std::endl;
CloseHandle(hFile);
return 0;
}
Best Practices
- Prefer
FILE_FLAG_OVERLAPPED
for high‑performance asynchronous I/O. - Always validate the return values of API calls and call
GetLastError
on failure. - Use
FILE_SHARE_READ
andFILE_SHARE_WRITE
flags judiciously to control concurrent access. - Close handles promptly to avoid resource leaks.