WriteFile

Function

BOOL WriteFile(
  HANDLE       hFile,
  const VOID   *lpBuffer,
  DWORD        nNumberOfBytesToWrite,
  LPDWORD      lpNumberOfBytesWritten,
  LPOVERLAPPED *lpOverlapped
);

Parameters

Parameter Description
hFile A handle to the file that is to be written to. This handle must have been created by the CreateFile function or by another function that returns a handle to a file.

This parameter can be `INVALID_HANDLE_VALUE` if the file is not opened with `CreateFile`.
lpBuffer A pointer to a buffer that contains the data to be written to the file.
nNumberOfBytesToWrite The number of bytes to write to the file.
lpNumberOfBytesWritten A pointer to a 32-bit unsigned integer variable that receives the number of bytes actually written when using a synchronous I/O operation and not setting the `OVERLAPPED` structure’s `hEvent` member.

If `lpOverlapped` is not `NULL` (meaning this is an asynchronous operation), the parameter is usually `NULL`. The value is put in the `OVERLAPPED` structure.
lpOverlapped A pointer to an OVERLAPPED structure, which is required for asynchronous operation. See the OVERLAPPED structure topic for more information.

If this parameter is `NULL`, `WriteFile` performs a synchronous operation.

Return Value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To write data to a file, you must open the file with the GENERIC_WRITE access right.

If hFile is a handle to a console buffer, the function only writes characters to the buffer. The cursor position does not change.

Note

A return value of TRUE and *lpNumberOfBytesWritten being less than nNumberOfBytesToWrite indicates that the data was buffered in memory, but not yet written to disk. If the application terminates without calling FlushFileBuffers, the data may be lost.

For file handles, WriteFile can operate in either synchronous or asynchronous mode. You can determine and set the mode of a file handle by using the SetFileCompletionNotificationModes function. For more information, see File I/O Completion Ports.

To write data to a file as an asynchronous operation, specify a pointer to an OVERLAPPED structure as the lpOverlapped parameter. If this is an asynchronous operation, lpOverlapped must point to a valid OVERLAPPED structure that contains a handle to an event object that is set when the write operation is complete.

If hFile is opened with the FILE_FLAG_RANDOM_ACCESS, FILE_FLAG_SEQUENTIAL_SCAN, or FILE_FLAG_NO_BUFFERING creation flags, there can be performance implications.

If lpOverlapped is NULL, WriteFile returns when the data has been transferred to the system buffer.

Important Security Notice

When writing to a file, always validate the input data and ensure that you are not overwriting critical system files or sensitive user data. Consider using secure file access patterns and checking file permissions before writing.

Example

For an example of how to use WriteFile, see Creating and Writing to a File.

/*
 * This code snippet demonstrates a basic usage of WriteFile.
 * It opens a file, writes some data, and closes the handle.
 * For a complete example, please refer to the official documentation.
 */

#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hFile;
    DWORD dwBytesWritten;
    LPCTSTR lpData = TEXT("This is some data to write to the file.\r\n");
    BOOL bErrorFlag;

    // Open the file for writing.
    hFile = CreateFile(
        TEXT("MyNewFile.txt"),      // Filename
        GENERIC_WRITE,              // Desired access
        0,                          // Share mode
        NULL,                       // Security attributes
        CREATE_ALWAYS,              // Creation disposition
        FILE_ATTRIBUTE_NORMAL,      // Flags and attributes
        NULL);                      // Template file

    if (hFile == INVALID_HANDLE_VALUE) {
        printf("Could not open file (Error %lu)\n", GetLastError());
        return 1;
    }

    // Write data to the file.
    bErrorFlag = WriteFile(
        hFile,           // Open file handle
        lpData,          // Data to write
        lstrlen(lpData) * sizeof(TCHAR), // Number of bytes to write
        &dwBytesWritten, // Number of bytes written
        NULL);           // Not using overlapped I/O

    if (bErrorFlag == FALSE) {
        printf("Error writing to file (Error %lu)\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    printf("Successfully wrote %lu bytes to the file.\n", dwBytesWritten);

    // Close the file handle.
    CloseHandle(hFile);

    return 0;
}