Read and Write Files with CreateFile and ReadFile
Open, create, read, write, append and seek files with CreateFileW, ReadFile and WriteFile, with share modes, dispositions and error codes explained.

The C library's fopen and fread work on Windows, and for plain files they are enough. The Win32 functions underneath them do more: they let you say who else may open the file while you have it, decide exactly what happens if it already exists, ask for a file to be deleted when closed, open devices and pipes with the same call, and read at a position without moving a shared file pointer. They also report failures with precise codes. This post covers the file functions you need for ordinary work: CreateFileW, ReadFile, WriteFile, SetFilePointerEx, GetFileSizeEx and FlushFileBuffers, with programs that write, read back, append and seek, and the table of codes that explain failures.
The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64. Each function is documented on Microsoft Learn, and the share mode rules in the page for CreateFileW are worth reading in full.
One function opens everything
CreateFileW is badly named. It opens existing files as readily as it creates new ones, and it opens devices, pipes, the console and directories too. The six arguments that matter:
HANDLE CreateFileW(
LPCWSTR path, /* file name, or a device or pipe name */
DWORD access, /* what you want to do */
DWORD share_mode, /* what others may do while you hold it */
LPSECURITY_ATTRIBUTES sa,
DWORD disposition, /* what to do if it exists, or does not */
DWORD flags, /* attributes and behavior flags */
HANDLE template_file); /* almost always NULL */Access is a bit mask. GENERIC_READ and GENERIC_WRITE cover most uses, and finer rights exist: FILE_APPEND_DATA lets you add to the end without permission to overwrite, and DELETE allows deleting through the handle. Ask for the least you need.
Disposition is a choice, not a mask:
| Value | If the file exists | If it does not |
|---|---|---|
CREATE_NEW | Fails with ERROR_FILE_EXISTS | Creates it |
CREATE_ALWAYS | Truncates it | Creates it |
OPEN_EXISTING | Opens it | Fails with ERROR_FILE_NOT_FOUND |
OPEN_ALWAYS | Opens it | Creates it |
TRUNCATE_EXISTING | Truncates it (needs write access) | Fails |
CREATE_NEW is the safe way to make a file only if nobody else has, which closes a race between "does it exist" and "create it". For OPEN_ALWAYS and CREATE_ALWAYS, GetLastError returns ERROR_ALREADY_EXISTS even on success when the file was already there, which lets you tell the cases apart.
Share mode is the part with no POSIX counterpart. It declares what other opens of the same file may do while yours is open: FILE_SHARE_READ lets others open for reading, FILE_SHARE_WRITE for writing, FILE_SHARE_DELETE lets them delete or rename it. A share mode of 0 means exclusive. Two opens conflict if either asks for access the other did not share, and the later one fails with ERROR_SHARING_VIOLATION, error 32. This is the cause of the familiar Windows message that a file is in use by another process. If you want Unix-like behavior, where other programs can read, replace and delete a file you have open, pass all three share flags.
Write a file and read it back
#include <windows.h>
#include <stdio.h>
#include <string.h>
static int fail(const wchar_t *what)
{
fwprintf(stderr, L"%ls failed: %lu\n", what, GetLastError());
return 1;
}
int wmain(void)
{
const char text[] = "line one\r\nline two\r\n";
DWORD n;
HANDLE w = CreateFileW(L"notes.txt", GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (w == INVALID_HANDLE_VALUE)
return fail(L"create");
if (!WriteFile(w, text, (DWORD)strlen(text), &n, NULL) || n != strlen(text)) {
CloseHandle(w);
return fail(L"write");
}
CloseHandle(w);
HANDLE r = CreateFileW(L"notes.txt", GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (r == INVALID_HANDLE_VALUE)
return fail(L"open");
LARGE_INTEGER size;
if (!GetFileSizeEx(r, &size)) {
CloseHandle(r);
return fail(L"GetFileSizeEx");
}
wprintf(L"size: %lld bytes\n", size.QuadPart);
char buf[256];
if (!ReadFile(r, buf, sizeof buf - 1, &n, NULL)) {
CloseHandle(r);
return fail(L"read");
}
buf[n] = '\0';
printf("read %lu bytes:\n%s", n, buf);
CloseHandle(r);
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE roundtrip.c
roundtrip.exeroundtrip.c
size: 20 bytes
read 20 bytes:
line one
line twoThe size is 20: eight characters and a two-byte line ending, twice. The details to take from the program are these.
WriteFile reports success and a byte count, and a careful program checks both. A true return with a smaller count is a partial write, which can happen on a full disk or with some device types. ReadFile returns true and sets the count to 0 when it reaches the end of the file, so the end is signaled by a zero count and not by a failure. A read loop therefore runs while (ReadFile(...) && got > 0).
The buffer passed to ReadFile is raw bytes. If the file is text, it is the program's job to know the encoding: UTF-8, UTF-16 with a byte-order mark, or a legacy code page. Win32 does no translation, which differs from fopen in text mode, where the C runtime converts line endings. The carriage return and line feed pairs came through untouched.
GetFileSizeEx fills a LARGE_INTEGER, a union that holds a 64-bit value, so files larger than 4 GiB report correctly. The older GetFileSize returned the low 32 bits and needed a second pointer for the high half, and is easy to misuse.
Reading a whole file
When a file is small, read it in one step by asking for its size and allocating that much:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
static char *slurp(const wchar_t *path, DWORD *out_len)
{
HANDLE h = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (h == INVALID_HANDLE_VALUE)
return NULL;
LARGE_INTEGER size;
if (!GetFileSizeEx(h, &size) || size.QuadPart > 64 * 1024 * 1024) {
CloseHandle(h);
return NULL;
}
char *data = malloc((size_t)size.QuadPart + 1);
DWORD got = 0, total = 0;
while (data && total < size.QuadPart &&
ReadFile(h, data + total, (DWORD)(size.QuadPart - total), &got, NULL) &&
got > 0)
total += got;
CloseHandle(h);
if (!data)
return NULL;
data[total] = '\0';
*out_len = total;
return data;
}
int wmain(int argc, wchar_t **argv)
{
if (argc != 2)
return 2;
DWORD len;
char *p = slurp(argv[1], &len);
if (!p) {
fwprintf(stderr, L"cannot read %ls: %lu\n", argv[1], GetLastError());
return 1;
}
printf("%lu bytes\n", len);
free(p);
return 0;
}20 bytesThe program caps the size at 64 MiB so a huge or hostile file cannot exhaust memory, and loops on ReadFile because a single call may return fewer bytes than requested. FILE_FLAG_SEQUENTIAL_SCAN hints to the cache manager that the file will be read from start to end, so it reads ahead more aggressively. Other hints are FILE_FLAG_RANDOM_ACCESS, the opposite, and FILE_FLAG_NO_BUFFERING, which bypasses the cache and demands that buffers and sizes be multiples of the sector size. Use that last one only when you know why.
For large files, a loop with a fixed-size buffer, say 64 KiB, beats reading everything at once. For random access to a big file, memory mapping is often better, as the file mapping post shows.
Appending and seeking
Windows has no O_APPEND, but it offers two ways to get the effect. Open with FILE_APPEND_DATA access and without FILE_WRITE_DATA, and every write goes to the end of the file atomically, even from several processes. Or seek to the end and write, which is not atomic across processes.
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
HANDLE h = CreateFileW(L"notes.txt", FILE_APPEND_DATA, FILE_SHARE_READ, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
fwprintf(stderr, L"open failed: %lu\n", GetLastError());
return 1;
}
const char more[] = "line three\r\n";
DWORD n;
WriteFile(h, more, sizeof more - 1, &n, NULL);
LARGE_INTEGER pos;
LARGE_INTEGER zero = { 0 };
SetFilePointerEx(h, zero, &pos, FILE_CURRENT);
wprintf(L"position after append: %lld\n", pos.QuadPart);
CloseHandle(h);
return 0;
}position after append: 32After the earlier program wrote 20 bytes, appending 12 more gives 32. SetFilePointerEx moves the position, with a 64-bit offset, relative to FILE_BEGIN, FILE_CURRENT or FILE_END, and returns the new position. A move of zero from the current position is the idiom for "where am I". Seeking past the end and writing extends the file, and the skipped region reads back as zeros.
One more way to read or write at a position is to pass an OVERLAPPED structure whose Offset fields hold the position, even on a handle opened without the overlapped flag. This reads from an offset without changing the file pointer, which is the safe form when several threads share one handle.
Making sure data reaches the disk
WriteFile returns when the data is in the system's file cache, not when it is on the disk. A power failure at that moment loses it. To force it out, call FlushFileBuffers(h) before closing, which asks the file system and the device to write everything. It is slow, and it should be used at the points where durability matters, such as after finishing a record that must survive a crash. Opening with FILE_FLAG_WRITE_THROUGH makes every write go to the device, which is a heavier setting with a similar purpose.
For replacing a file safely, write the new contents to a temporary file in the same directory, flush it, then swap it into place with MoveFileExW(tmp, final, MOVEFILE_REPLACE_EXISTING), or ReplaceFileW when you want a backup. That way a crash leaves either the old file or the new one, never half of each.
Deleting on close and other flags
FILE_FLAG_DELETE_ON_CLOSE makes Windows remove the file when the last handle closes, which suits temporary files and requires the DELETE access right in CreateFileW or a share mode that allows it. FILE_ATTRIBUTE_TEMPORARY hints that the file should stay in cache. FILE_FLAG_BACKUP_SEMANTICS is required to open a directory handle. FILE_FLAG_OVERLAPPED selects asynchronous I/O, and then every read and write must pass an OVERLAPPED.
Reading failures
Most open failures fall in a short list:
| Code | Name | Usual cause |
|---|---|---|
| 2 | ERROR_FILE_NOT_FOUND | The file does not exist |
| 3 | ERROR_PATH_NOT_FOUND | A directory in the path does not exist |
| 5 | ERROR_ACCESS_DENIED | No permission, or it is a directory, or read-only |
| 32 | ERROR_SHARING_VIOLATION | Another open has the file without a compatible share mode |
| 80 | ERROR_FILE_EXISTS | CREATE_NEW on a name that exists |
| 123 | ERROR_INVALID_NAME | Illegal characters or a malformed path |
| 183 | ERROR_ALREADY_EXISTS | Informational with OPEN_ALWAYS and CREATE_ALWAYS |
Access denied on a path that you own often means the target is a directory: opening a directory needs FILE_FLAG_BACKUP_SEMANTICS. A sharing violation on a log file usually means an antivirus scanner or an indexer has it open, and retrying after a short delay is the pragmatic answer.
Where this is the wrong tool
For text files read by line, the C library's fgets and fopen are shorter and portable. For structured data, a database or a serialization library beats hand-managed bytes. For huge files accessed in many places, memory mapping, or at least FILE_FLAG_RANDOM_ACCESS, beats sequential reads. The Win32 file API is for control: share modes, security, atomic append, devices and asynchronous I/O.


