File System

The Win32 file system API is fairly straight forward. It's all handle based, and just a few functions. Creeating and opening a file can be done with CreateFile / CreateFileW / CreateFileA, don't forget to close the handle that these functions return. You can query the size of the a file with GetFileSize.

The C / C++ API functions that read and write files are buffered. These windows functions are not. If you're reading small chunks, performance will be worse.

This code sample shows how to read all bytes from a file.

const char* path = "C:/file.txt";
void* data = malloc(1024*1024);
unsigned int bytes = 1024*1024;

HANDLE hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD bytesInFile = GetFileSize(hFile, 0);
DWORD bytesRead = 0;

if (bytesInFile > bytes) {
    bytesInFile = bytes;
}

if (hFile != INVALID_HANDLE_VALUE) {
    if (ReadFile(hFile, target, bytesInFile, &bytesRead, NULL) != 0) {
        // File is read / ready to use. It's in data and bytesRead.
    }

    CloseHandle(hFile);
}

And this code sample shows how to write to a file:

const char* path = "C:/file.txt";
void* data = & structtowrite;
DWORD bytes = sizeof(structtowrite);
DWORD written = 0;

HANDLE hFile = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
    WriteFile(hFile, data, (DWORD)bytes, &written, NULL);
    assert(written == bytes);
    CloseHandle(hFile);
}