Overview
The File I/O (Input/Output) API provides a set of functions for creating, reading, writing, and managing files and directories on Windows operating systems. These functions allow developers to interact with the file system directly, handling data streams, file attributes, security descriptors, and asynchronous operations.
Core Functions
| Function | Purpose | Header |
|---|---|---|
CreateFile | Opens or creates a file or I/O device. | Windows.h |
ReadFile | Reads data from a file or device. | Windows.h |
WriteFile | Writes data to a file or device. | Windows.h |
CloseHandle | Closes an open object handle. | Windows.h |
SetFilePointer | Moves the file pointer. | Windows.h |
GetFileSizeEx | Retrieves the size of a file. | Windows.h |
DeleteFile | Deletes an existing file. | Windows.h |
CopyFile | Copies an existing file to a new file. | Windows.h |
MoveFileEx | Moves or renames a file. | Windows.h |
GetFileAttributes | Retrieves file attributes. | Windows.h |
Sample Code – Reading a Text File
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hFile = CreateFile(
L"example.txt", // file name
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // open existing file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (hFile == INVALID_HANDLE_VALUE) {
wprintf(L"Failed to open file (error %lu)\n", GetLastError());
return 1;
}
DWORD fileSize = 0;
LARGE_INTEGER size;
if (!GetFileSizeEx(hFile, &size)) {
wprintf(L"Failed to get size (error %lu)\n", GetLastError());
CloseHandle(hFile);
return 1;
}
fileSize = (DWORD)size.QuadPart;
char *buffer = (char*)malloc(fileSize + 1);
if (!buffer) {
wprintf(L"Memory allocation failed\n");
CloseHandle(hFile);
return 1;
}
DWORD bytesRead;
if (!ReadFile(hFile, buffer, fileSize, &bytesRead, NULL) || bytesRead != fileSize) {
wprintf(L"Read error (error %lu)\n", GetLastError());
free(buffer);
CloseHandle(hFile);
return 1;
}
buffer[bytesRead] = '\0'; // Null‑terminate
printf("File contents:\\n%s\\n", buffer);
free(buffer);
CloseHandle(hFile);
return 0;
}