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

WriteFile function (fileapi.h)

  • 2025-03-03
Feedback

In this article

Writes data to the specified file or input/output (I/O) device.

This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for asynchronous operation, seeWriteFileEx.

Syntax

BOOL WriteFile(  [in]                HANDLE       hFile,  [in]                LPCVOID      lpBuffer,  [in]                DWORD        nNumberOfBytesToWrite,  [out, optional]     LPDWORD      lpNumberOfBytesWritten,  [in, out, optional] LPOVERLAPPED lpOverlapped);

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

ThehFile parameter must have been created with the write access. For more information, seeGeneric Access Rights andFile Security and Access Rights.

For asynchronous write operations,hFile can be any handle opened with theCreateFile function using theFILE_FLAG_OVERLAPPED flag or a socket handle returned by thesocket oraccept function.

[in] 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 or communications technology.

Windows Server 2003 and Windows XP: Pipe write operations across a network are limited in size per write. The amount varies per platform. For x86 platforms it's 63.97 MB. For x64 platforms it's 31.97 MB. For Itanium it's 63.95 MB. For more information regarding pipes, see the Remarks section.

[out, optional] lpNumberOfBytesWritten

A pointer to the variable that receives the number of bytes written when using a synchronoushFile parameter.WriteFile sets this value to zero before doing any work or error checking. UseNULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can beNULL only when thelpOverlapped parameter is notNULL.

Windows 7: This parameter can not beNULL.

For more information, see the Remarks section.

[in, out, optional] lpOverlapped

A pointer to anOVERLAPPED structure is required if thehFile parameter was opened withFILE_FLAG_OVERLAPPED, otherwise this parameter can beNULL.

For anhFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start writing to the file or device. This offset is specified by setting theOffset andOffsetHigh members of theOVERLAPPED structure. For anhFile that does 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.

For more information about different combinations oflpOverlapped andFILE_FLAG_OVERLAPPED, see the Remarks section and theSynchronization and File Position section.

Return value

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call theGetLastError function.

Note

 TheGetLastError codeERROR_IO_PENDING is not a failure; it designates the write operation is pending completion asynchronously. For more information, seeRemarks.

Remarks

TheWriteFile function returns when one of the following conditions occur:

  • The number of bytes requested is written.
  • A read operation releases buffer space on the read end of the pipe (if the write was blocked). For more information, see thePipes section.
  • An asynchronous handle is being used and the write is occurring asynchronously.
  • An error occurs.

TheWriteFile function may fail withERROR_INVALID_USER_BUFFER orERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

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

  • CancelIo — This function cancels only 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 theCancelSynchronousIo function to cancel pending synchronous I/O operations.

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

TheWriteFile function may fail withERROR_NOT_ENOUGH_QUOTA, which means the calling process's buffer could not be page-locked. For more information, seeSetProcessWorkingSetSize.

If part of the file is locked by another process and the write operation overlaps the locked portion,WriteFile 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. This can be particularly problematic when using an asynchronous file handle. Additional information regarding synchronous versus asynchronous file handles can be found later in theSynchronization and File Position section andSynchronous and Asynchronous I/O.

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.

Characters can be written to the screen buffer usingWriteFile with a handle to console output. The exact behavior of the function is determined by the console mode. The data is written to the current cursor position. The cursor position is updated after the write operation. For more information about console handles, seeCreateFile.

When writing to a communications device, the behavior ofWriteFile is determined by the current communication time-out as set and retrieved by using theSetCommTimeouts andGetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, seeCOMMTIMEOUTS.

Although a single-sector write is atomic, a multi-sector write is not guaranteed to be atomic unless you are using a transaction (that is, the handle created is a transacted handle; for example, a handle created usingCreateFileTransacted). Multi-sector writes that are cached may not always be written to the disk right away; therefore, specifyFILE_FLAG_WRITE_THROUGH inCreateFile to ensure that an entire multi-sector write is written to the disk without potential caching delays.

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.

IfhFile was opened withFILE_FLAG_OVERLAPPED, the following conditions are in effect:

  • ThelpOverlapped parameter must point to a valid and uniqueOVERLAPPED structure, otherwise the function can incorrectly report that the write operation is complete.
  • ThelpNumberOfBytesWritten parameter should be set toNULL. To get the number of bytes written, use theGetOverlappedResult function. If thehFile parameter is associated with an I/O completion port, you can also get the number of bytes written by calling theGetQueuedCompletionStatus function.

In 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

Synchronization and File Position

IfhFile is opened withFILE_FLAG_OVERLAPPED, it is an asynchronous file handle; otherwise it is synchronous. The rules for using theOVERLAPPED structure are slightly different for each, as previously noted.

Note

 If a file or device is opened for asynchronous I/O, subsequent calls to functions such asWriteFile using that handle generally return immediately, but can also behave synchronously with respect to blocked execution. For more information, seeAsynchronous disk I/O appears as synchronous on Windows.

Considerations for working with asynchronous file handles:

  • WriteFile may return before the write operation is complete. In this scenario,WriteFile returnsFALSE and theGetLastError function returnsERROR_IO_PENDING, which allows the calling process to continue while the system completes the write operation.
  • ThelpOverlapped parameter must not beNULL and should be used with the following facts in mind:
    • Although the event specified in theOVERLAPPED structure is set and reset automatically by the system, the offset that is specified in theOVERLAPPED structure is not automatically updated.
    • WriteFile resets the event to a non-signaled state when it begins the I/O operation.
    • The event specified in theOVERLAPPED structure is set to a signaled state when the write operation is complete; until that time, the write operation is considered pending.
    • Because the write operation starts at the offset that is specified in theOVERLAPPED structure, andWriteFile may return before the system-level write operation is complete (write pending), neither the offset nor any other part of the structure should be modified, freed, or reused by the application until the event is signaled (that is, the write completes).

Considerations for working with synchronous file handles:

  • IflpOverlapped isNULL, the write operation starts at the current file position andWriteFile does not return until the operation is complete, and the system updates the file pointer beforeWriteFile returns.
  • IflpOverlapped is notNULL, the write operation starts at the offset that is specified in theOVERLAPPED structure andWriteFile does not return until the write operation is complete. The system updates theOVERLAPPEDInternal andInternalHigh fields and the file pointer beforeWriteFile returns.

For more information, seeCreateFile andSynchronous and Asynchronous I/O.

Pipes

If an anonymous pipe is being used and the read handle has been closed, whenWriteFile attempts to write using the pipe's corresponding write handle, the function returnsFALSE andGetLastError returnsERROR_BROKEN_PIPE.

If the pipe buffer is full when an application uses theWriteFile function to write to a pipe, the write operation may not finish immediately. The write operation will be completed when a read operation (using theReadFile function) makes more system buffer space available for the pipe.

When writing to a non-blocking, byte-mode pipe handle with insufficient buffer space,WriteFile returnsTRUE with*lpNumberOfBytesWritten <nNumberOfBytesToWrite.

For more information about pipes, seePipes.

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 some examples, seeCreating and Using a Temporary File andOpening a File for Reading or Writing.

The following C++ example shows how to align sectors for unbuffered file writes. TheSize variable is the size of the original data block you are interested in writing to the file. For additional rules regarding unbuffered file I/O, seeFile Buffering.

#include <windows.h>#define ROUND_UP_SIZE(Value,Pow2) ((SIZE_T) ((((ULONG)(Value)) + (Pow2) - 1) & (~(((LONG)(Pow2)) - 1))))#define ROUND_UP_PTR(Ptr,Pow2)  ((void *) ((((ULONG_PTR)(Ptr)) + (Pow2) - 1) & (~(((LONG_PTR)(Pow2)) - 1))))int main(){   // Sample data   unsigned long bytesPerSector = 65536; // obtained from the GetFreeDiskSpace function.   unsigned long size = 15536; // Buffer size of your data to write.      // Ensure you have one more sector than Size would require.   size_t sizeNeeded = bytesPerSector + ROUND_UP_SIZE(size, bytesPerSector);      // Replace this statement with any allocation routine.   auto buffer = new uint8_t[sizeNeeded];      // Actual alignment happens here.   auto bufferAligned = ROUND_UP_PTR(buffer, bytesPerSector);   // ... Add code using bufferAligned here.      // Replace with corresponding free routine.   delete buffer;}

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

CancelIo

CancelIoEx

CancelSynchronousIo

CreateFile

CreateFileTransacted

File Management Functions

GetLastError

GetOverlappedResult

GetQueuedCompletionStatus

ReadFile

SetEndOfFile

WriteFileEx


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo