Click to Rate and Give Feedback
MSDN
MSDN Library
Windows Development
Local File Systems
File Management
 WriteFileEx function
WriteFileEx function

Applies to: desktop apps only

Writes data to the specified file or input/output (I/O) device. It reports its completion status asynchronously, calling the specified completion routine when writing is completed or canceled and the calling thread is in an alertable wait state.

To write data to a file or device synchronously, use the WriteFile function.

Syntax

BOOL WINAPI WriteFileEx(
  __in      HANDLE hFile,
  __in_opt  LPCVOID lpBuffer,
  __in      DWORD nNumberOfBytesToWrite,
  __inout   LPOVERLAPPED lpOverlapped,
  __in_opt  LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

Parameters

hFile [in]

A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, communications resource, mailslot, or pipe).

This parameter can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept function.

Do not associate an I/O completion port with this handle. For more information, see the Remarks section.

This handle also must have the GENERIC_WRITE access right. For more information on access rights, see File Security and Access Rights.

lpBuffer [in, optional]

A pointer to the buffer containing the data to be written to the file or device.

This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

nNumberOfBytesToWrite [in]

The number of bytes to be written to the file or device.

A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system.

Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section.

lpOverlapped [in, out]

A pointer to an OVERLAPPED data structure that supplies data to be used during the overlapped (asynchronous) write operation.

For files that support byte offsets, you must specify a byte offset at which to start writing to the file. You specify this offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files or devices that do not support byte offsets, Offset and OffsetHigh are ignored.

To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open hFile using FILE_APPEND_DATA access.

The WriteFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a WriteFileEx call. WriteFileEx signals completion of its writing operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The WriteFileEx function does use the Internal and InternalHigh members of the OVERLAPPED structure. You should not change the value of these members.

The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that can go out of scope while the write operation is pending completion.

lpCompletionRoutine [in, optional]

A pointer to a completion routine to be called when the write operation has been completed and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.

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.

If the WriteFileEx function succeeds, the calling thread has an asynchronous I/O operation pending: the overlapped write operation to the file. When this I/O operation finishes, and the calling thread is blocked in an alertable wait state, the operating system calls the function pointed to by lpCompletionRoutine, and the wait completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds and the file-writing operation finishes, but the calling thread is not in an alertable wait state, the system queues the call to *lpCompletionRoutine, holding the call until the calling thread enters an alertable wait state. For more information about alertable wait states and overlapped input/output operations, see About Synchronization.

Remarks

When using WriteFileEx you should check GetLastError even when the function returns "success" to check for conditions that are "successes" but have some outcome you might want to know about. For example, a buffer overflow when calling WriteFileEx will return TRUE, but GetLastError will report the overflow with ERROR_MORE_DATA. If the function call is successful and there are no warning conditions, GetLastError will return ERROR_SUCCESS.

The WriteFileEx function will fail if the hFile parameter is associated with an I/O completion port. To perform writes using this type of handle, use the WriteFile function.

The WriteFileEx function may fail if there are too many outstanding asynchronous I/O requests. In the event of such a failure, GetLastError can return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY.

To cancel all pending asynchronous I/O operations, use either:

  • CancelIo—this function only cancels operations issued by the calling thread for the specified file handle.
  • CancelIoEx—this function cancels all operations issued by the threads for the specified file handle.

Use CancelSynchronousIo to cancel pending synchronous I/O operations.

I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.

If part of the file specified by hFile is locked by another process, and the specified write operation overlaps the locked portion, WriteFileEx fails.

When writing to a file, the last write time is not fully updated until all handles used for writing have been closed. Therefore, to ensure an accurate last write time, close the file handle immediately after writing to the file.

Accessing the output buffer while a write operation is using the buffer may lead to corruption of the data written from that buffer. Applications must not write to, reallocate, or free the output buffer that a write operation is using until the write operation completes.

Note that the time stamps may not be updated correctly for a remote file. To ensure consistent results, use unbuffered I/O.

The system interprets zero bytes to write as specifying a null write operation and WriteFile does not truncate or extend the file. To truncate or extend a file, use the SetEndOfFile function.

An application uses the WaitForSingleObjectEx, WaitForMultipleObjectsEx, MsgWaitForMultipleObjectsEx, SignalObjectAndWait, and SleepEx functions to enter an alertable wait state. For more information about alertable wait states and overlapped I/O operations, see About Synchronization.

If you write directly to a volume that has a mounted file system, you must first obtain exclusive access to the volume. Otherwise, you risk causing data corruption or system instability, because your application's writes may conflict with other changes coming from the file system and leave the contents of the volume in an inconsistent state. To prevent these problems, the following changes have been made in Windows Vista and later:

  • A write on a volume handle will succeed if the volume does not have a mounted file system, or if one of the following conditions is true:
    • The sectors to be written to are boot sectors.
    • The sectors to be written to reside outside of file system space.
    • You have explicitly locked or dismounted the volume by using FSCTL_LOCK_VOLUME or FSCTL_DISMOUNT_VOLUME.
    • The volume has no actual file system. (In other words, it has a RAW file system mounted.)
  • A write on a disk handle will succeed if one of the following conditions is true:
    • The sectors to be written to do not fall within a volume's extents.
    • The sectors to be written to fall within a mounted volume, but you have explicitly locked or dismounted the volume by using FSCTL_LOCK_VOLUME or FSCTL_DISMOUNT_VOLUME.
    • The sectors to be written to fall within a volume that has no mounted file system other than RAW.

There are strict requirements for successfully working with files opened with CreateFile using FILE_FLAG_NO_BUFFERING. For details see File Buffering.

Transacted Operations

If there is a transaction bound to the file handle, then the file write is transacted. For more information, see About Transactional NTFS.

Examples

For an example, see Named Pipe Server Using Completion Routines.

Requirements

Minimum supported client

Windows XP

Minimum supported server

Windows Server 2003

Header

FileAPI.h (include Windows.h);
WinBase.h on Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP (include Windows.h)

Library

Kernel32.lib

DLL

Kernel32.dll

See also

CancelIo
CancelIoEx
CancelSynchronousIo
CreateFile
File Management Functions
FileIOCompletionRoutine
MsgWaitForMultipleObjectsEx
ReadFileEx
SetEndOfFile
SetErrorMode
SleepEx
SignalObjectAndWait
WaitForMultipleObjectsEx
WaitForSingleObjectEx
WriteFile

 

 

Send comments about this topic to Microsoft

Build date: 4/17/2012

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
The last-error code is not set to ERROR_SUCCESS if the function is successful      Harry Johnston   |   Edit   |   Show History
Despite what this documentation says, WriteFileEx does not set the last-error code to ERROR_SUCCESS when the function is successful.  The last-error code remains unchanged.  This is easy to verify by calling SetLastError before WriteFileEx.

So if the return value is nonzero, don't call GetLastError.  You'll get spurious results.

Tags What's this?: Add a tag
Flag as ContentBug
Max pipe write chunk less than 64MB      DanMoseley - MSFT ... Harry Johnston   |   Edit   |   Show History

"Pipe write operations across a network are limited to 65,535 bytes per write"

Actually it's apparently slightly less: about 63.95 MB, and just under 32MB on x64. From elsewhere:

[Actually, 63.95MB is a lot more than 65,535 bytes, not slightly less! - Harry Johnston]

The reason for the ERROR_NO_SYSTEM_RESOURCES(1450) is that on x86 (32-bit) or IA64 (64-bit) systems, the maximum buffer size is just under 64MB. For X64 systems, the maximum buffer size is just under 32MB. The maximum unbuffered read and write size limits are imposed by the design of the IO manager inside the Windows executive. When an application reads or writes files that are opened with FILE_FLAG_NO_BUFFERING, the IO Manager locks the application's buffer into physical RAM and then maps the virtual addresses into physical addresses to pass to the disk device by making a memory descriptor list (MDL). The buffer size limitation comes from the maximum size MDL that the IO Manager will create. The reason for the difference between platforms is the way the maximum buffer size is calculated from the memory page size and pointer size. The IO Manager uses the following formula to compute the maximum size MDL:

((65535 - sizeof(MDL)) / sizeof(ULONG_PTR)) * PAGE_SIZE

This formula has the following results:

Processor Page Size Pointer Size MDL calculation
======== ======== ========= =============

x86 (32-bit) 4096 4 bytes ((65535 - 28) / 4) * 4096 = 67076096 bytes (63.97 MB)

IA64 8096 8 bytes ((65535 - 48) / 8) * 8192 = 67051520 bytes (63.95 MB)

X64 4096 8 bytes ((65535 - 48) / 8) * 4096 = 33525760 bytes (32MB - 28K)

This limitation occurs when the file is opened with FILE_FLAG_NO_BUFFERING.

Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker