Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Setup File Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Zip File
WriteFile is a Win32 File API to write 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, see WriteFileEx.
BOOL WriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped );
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).
The hFile parameter must have been created with the write access. For more information, see Generic Access Rights and File Security and Access Rights.
For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the FILE_FLAG_OVERLAPPEDflag or a socket handle returned by the socket or accept function.
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.
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.
lpNumberOfBytesWritten
A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
For more information, see the Remarks section.
lpOverlapped
A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL.
For an hFile 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 the Offset and OffsetHigh members of the OVERLAPPED structure. For an hFile that does 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.
For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and theSynchronization and File Position section.
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.
The WriteFile function returns when one of the following conditions occur:
To cancel all pending asynchronous I/O operations, use either:
I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.
The WriteFile function may fail with ERROR_NOT_ENOUGH_QUOTA, which means the calling process's buffer could not be page-locked. For more information, see SetProcessWorkingSetSize.
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 the Synchronization and File Position section and Synchronous 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 and WriteFile does not truncate or extend the file. To truncate or extend a file, use the SetEndOfFile function.
Characters can be written to the screen buffer using WriteFile 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, see CreateFile.
When writing to a communications device, the behavior of WriteFile is determined by the current communication time-out as set and retrieved by using the SetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, see COMMTIMEOUTS.
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 using CreateFileTransacted). Multi-sector writes that are cached may not always be written to the disk right away; therefore, specify FILE_FLAG_WRITE_THROUGH in CreateFile 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:
If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:
Technology | Supported |
---|---|
Server Message Block (SMB) 3.0 protocol | Yes |
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 |
If the pipe buffer is full when an application uses the WriteFile function to write to a pipe, the write operation may not finish immediately. The write operation will be completed when a read operation (using the ReadFile 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 returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.
The following example uses CreateFile to create a new file and open it for writing and WriteFile to write a simple string synchronously to the file.
A subsequent call to open this file with CreateFile will fail until the handle is closed.
#include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h>void DisplayError(LPTSTR lpszFunction); void __cdecl _tmain(int argc, TCHAR *argv[]) { HANDLE hFile; char DataBuffer[] = "This is some test data to write to the file."; DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer); DWORD dwBytesWritten = 0; BOOL bErrorFlag = FALSE; printf("\n"); if( argc != 2 ) { printf("Usage Error:\tIncorrect number of arguments\n\n"); _tprintf(TEXT("%s \n"), argv[0]); return; } hFile = CreateFile(argv[1], // name of the write GENERIC_WRITE, // open for writing 0, // do not share NULL, // default security CREATE_NEW, // create new file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template if (hFile == INVALID_HANDLE_VALUE) { DisplayError(TEXT("CreateFile")); _tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), argv[1]); return; } _tprintf(TEXT("Writing %d bytes to %s.\n"), dwBytesToWrite, argv[1]); bErrorFlag = WriteFile( hFile, // open file handle DataBuffer, // start of data to write dwBytesToWrite, // number of bytes to write &dwBytesWritten, // number of bytes that were written NULL); // no overlapped structure if (FALSE == bErrorFlag) { DisplayError(TEXT("WriteFile")); printf("Terminal failure: Unable to write to file.\n"); } else { if (dwBytesWritten != dwBytesToWrite) { // This is an error because a synchronous write that results in // success (WriteFile returns TRUE) should write all data as // requested. This would not necessarily be the case for // asynchronous writes. printf("Error: dwBytesWritten != dwBytesToWrite\n"); } else { _tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, argv[1]); } } CloseHandle(hFile); } void DisplayError(LPTSTR lpszFunction) // Routine Description: // Retrieve and output the system error message for the last-error code { LPVOID lpMsgBuf; LPVOID lpDisplayBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); lpDisplayBuf = (LPVOID)LocalAlloc( LMEM_ZEROINIT, ( lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) // account for format string * sizeof(TCHAR) ); if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error code %d as follows:\n%s"), lpszFunction, dw, lpMsgBuf))) { printf("FATAL ERROR: Unable to output error code.\n"); } _tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf);