Key Functions
CreateFileW
Creates or opens a file or device for read/write access.
#include <windows.h>
HANDLE hFile = CreateFileW(
L"C:\\temp\\example.txt", // lpFileName
GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess
0, // dwShareMode
NULL, // lpSecurityAttributes
CREATE_ALWAYS, // dwCreationDisposition
FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes
NULL); // hTemplateFile
Copy
ReadFile
Reads data from the specified file or input/output (I/O) device.
#include <windows.h>
DWORD bytesRead;
char buffer[256];
BOOL result = ReadFile(
hFile, // hFile
buffer, // lpBuffer
sizeof(buffer), // nNumberOfBytesToRead
&bytesRead, // lpNumberOfBytesRead
NULL); // lpOverlapped
Copy
WriteFile
Writes data to the specified file or I/O device.
#include <windows.h>
DWORD bytesWritten;
const char *msg = "Hello, Windows file system!";
BOOL result = WriteFile(
hFile, // hFile
msg, // lpBuffer
(DWORD)strlen(msg), // nNumberOfBytesToWrite
&bytesWritten, // lpNumberOfBytesWritten
NULL); // lpOverlapped
Copy
DeleteFileW
Deletes an existing file.
#include <windows.h>
BOOL result = DeleteFileW(L"C:\\temp\\example.txt");
Copy
Complete Example: List Files in a Directory
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int main() {
WIN32_FIND_DATAW ffd;
HANDLE hFind = FindFirstFileW(L"C:\\temp\\*", &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
wprintf(L"FindFirstFile failed (error %lu)\\n", GetLastError());
return 1;
}
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
wprintf(L"[DIR] %s\\n", ffd.cFileName);
else
wprintf(L" %s\\n", ffd.cFileName);
} while (FindNextFileW(hFind, &ffd) != 0);
FindClose(hFind);
return 0;
}
Copy