Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

WriteFileEx function (fileapi.h)

  • 2023-02-13
Feedback

In this article

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 theWriteFile function.

Syntax

BOOL WriteFileEx(  [in]           HANDLE                          hFile,  [in, optional] LPCVOID                         lpBuffer,  [in]           DWORD                           nNumberOfBytesToWrite,  [in, out]      LPOVERLAPPED                    lpOverlapped,  [in]           LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);

Parameters

[in] hFile

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 theFILE_FLAG_OVERLAPPED flag by theCreateFile function, or a socket handle returned by thesocket oraccept function.

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

This handle also must have theGENERIC_WRITE access right. For more information on access rights, seeFile Security and Access Rights.

[in, optional] lpBuffer

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.

[in] nNumberOfBytesToWrite

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.

[in, out] lpOverlapped

A pointer to anOVERLAPPED 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 theOffset andOffsetHigh members of theOVERLAPPED structure. For files or devices that do not support byte offsets,Offset andOffsetHigh are ignored.

To write to the end of file, specify both theOffset andOffsetHigh members of theOVERLAPPED structure as0xFFFFFFFF. This is functionally equivalent to previously calling theCreateFile function to openhFile usingFILE_APPEND_DATA access.

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

TheWriteFileEx function does use theInternal andInternalHigh members of theOVERLAPPED structure. You should not change the value of these members.

TheOVERLAPPED 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.

[in] lpCompletionRoutine

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, seeFileIOCompletionRoutine.

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, callGetLastError.

If theWriteFileEx 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 bylpCompletionRoutine, and the wait completes with a return code ofWAIT_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, seeAbout Synchronization.

Remarks

When usingWriteFileEx you should checkGetLastError even when the function returns "success" to check for conditions that aresuccesses but have some outcome you might want to know about. For example, a buffer overflow when callingWriteFileEx will returnTRUE, butGetLastError will report the overflow withERROR_MORE_DATA. If the function call is successful and there are no warning conditions,GetLastError will returnERROR_SUCCESS.

TheWriteFileEx function will fail if thehFile parameter is associated with anI/O completion port. To perform writes using this type of handle, use theWriteFile function.

TheWriteFileEx function may fail if there are too many outstanding asynchronous I/O requests. In the event of such a failure,GetLastError can returnERROR_INVALID_USER_BUFFER orERROR_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.

UseCancelSynchronousIo to cancel pending synchronous I/O operations.

I/O operations that are canceled complete with the errorERROR_OPERATION_ABORTED.

If part of the file specified byhFile 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 andWriteFile does not truncate or extend the file. To truncate or extend a file, use theSetEndOfFile function.

An application uses theWaitForSingleObjectEx,WaitForMultipleObjectsEx,MsgWaitForMultipleObjectsEx,SignalObjectAndWait, andSleepEx functions to enter an alertable wait state. For more information about alertable wait states and overlapped I/O operations, seeAbout 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 usingFSCTL_LOCK_VOLUME orFSCTL_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 usingFSCTL_LOCK_VOLUME orFSCTL_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 withCreateFile usingFILE_FLAG_NO_BUFFERING. For details seeFile Buffering.

In Windows 8 and Windows Server 2012, this function is supported by the following technologies.

TechnologySupported
Server Message Block (SMB) 3.0 protocolYes
SMB 3.0 Transparent Failover (TFO)Yes
SMB 3.0 with Scale-out File Shares (SO)Yes
Cluster Shared Volume File System (CsvFS)Yes
Resilient File System (ReFS)Yes

Transacted Operations

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

Examples

For an example, seeNamed Pipe Server Using Completion Routines.

Requirements

RequirementValue
Minimum supported clientWindows XP [desktop apps | UWP apps]
Minimum supported serverWindows Server 2003 [desktop apps | UWP apps]
Target PlatformWindows
Headerfileapi.h (include Windows.h)
LibraryKernel32.lib
DLLKernel32.dll

See also


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo