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

ReadFile function (fileapi.h)

  • 2024-10-03
Feedback

In this article

Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device.

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

Syntax

BOOL ReadFile(  [in]                HANDLE       hFile,  [out]               LPVOID       lpBuffer,  [in]                DWORD        nNumberOfBytesToRead,  [out, optional]     LPDWORD      lpNumberOfBytesRead,  [in, out, optional] LPOVERLAPPED lpOverlapped);

Parameters

[in] hFile

A handle to the 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 read access. For more information, seeGeneric Access Rights andFile Security and Access Rights.

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

[out] lpBuffer

A pointer to the buffer that receives the data read from a file or device.

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

[in] nNumberOfBytesToRead

The maximum number of bytes to be read.

[out, optional] lpNumberOfBytesRead

A pointer to the variable that receives the number of bytes read when using a synchronoushFile parameter.ReadFile 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 it can beNULL.

IfhFile is opened withFILE_FLAG_OVERLAPPED, thelpOverlapped parameter must point to a valid and uniqueOVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.

For anhFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from 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.

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 read operation is pending completion asynchronously. For more information, see Remarks.

Remarks

TheReadFile function returns when one of the following conditions occur:

  • The number of bytes requested is read.
  • A write operation completes on the write end of the pipe.
  • An asynchronous handle is being used and the read is occurring asynchronously.
  • An error occurs.

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

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

If part of a file is locked by another process and the read operation overlaps the locked portion, this function fails.

Accessing the input buffer while a read operation is using the buffer may lead to corruption of the data read into that buffer. Applications must not read from, write to, reallocate, or free the input buffer that a read operation is using until the read operation completes. This can be particularly problematic when using an asynchronous file handle. Additional information regarding synchronous versus asynchronous file handles can be found in theSynchronization and File Position section and in theCreateFile reference topic.

Characters can be read from the console input buffer by usingReadFile with a handle to console input. The console mode determines the exact behavior of theReadFile function. By default, the console mode isENABLE_LINE_INPUT, which indicates thatReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, butGetLastError returnsERROR_OPERATION_ABORTED. For more information, seeCreateFile.

When reading from a communications device, the behavior ofReadFile 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.

IfReadFile attempts to read from a mailslot that has a buffer that is too small, the function returnsFALSE andGetLastError returnsERROR_INSUFFICIENT_BUFFER.

There are strict requirements for successfully working with files opened withCreateFile using theFILE_FLAG_NO_BUFFERING flag. 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 read operation is complete.
  • ThelpNumberOfBytesRead parameter should be set toNULL. Use theGetOverlappedResult function to get the actual number of bytes read. If thehFile parameter is associated with an I/O completion port, you can also get the number of bytes read by calling theGetQueuedCompletionStatus function.

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 asReadFile 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:

  • ReadFile may return before the read operation is complete. In this scenario,ReadFile returnsFALSE and theGetLastError function returnsERROR_IO_PENDING, which allows the calling process to continue while the system completes the read 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.
    • ReadFile resets the event to a nonsignaled state when it begins the I/O operation.
    • The event specified in theOVERLAPPED structure is set to a signaled state when the read operation is complete; until that time, the read operation is considered pending.
    • Because the read operation starts at the offset that is specified in theOVERLAPPED structure, andReadFile may return before the system-level read operation is complete (read 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 read completes).
    • If end-of-file (EOF) is detected during asynchronous operations, the call toGetOverlappedResult for that operation returnsFALSE andGetLastError returnsERROR_HANDLE_EOF.

Considerations for working with synchronous file handles:

  • IflpOverlapped isNULL, the read operation starts at the current file position andReadFile does not return until the operation is complete, and the system updates the file pointer beforeReadFile returns.
  • IflpOverlapped is notNULL, the read operation starts at the offset that is specified in theOVERLAPPED structure andReadFile does not return until the read operation is complete. The system updates theOVERLAPPED offset and the file pointer beforeReadFile returns.
  • IflpOverlapped isNULL, then when a synchronous read operation reaches the end of a file,ReadFile returnsTRUE and sets*lpNumberOfBytesRead to zero.
  • IflpOverlapped is notNULL, then when a synchronous read operation reaches the end of a file,ReadFile returnsFALSE andGetLastError returnsERROR_HANDLE_EOF.

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

Pipes

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

If a named pipe is being read in message mode and the next message is longer than thenNumberOfBytesToRead parameter specifies,ReadFile returnsFALSE andGetLastError returnsERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to theReadFile orPeekNamedPipe function.

If thelpNumberOfBytesRead parameter is zero whenReadFile returnsTRUE on a pipe, the other end of the pipe called theWriteFile function withnNumberOfBytesToWrite set to zero.

For more information about pipes, seePipes.

Transacted Operations

If there is a transaction bound to the file handle, then the function returns data from the transacted view of the file. A transacted read handle is guaranteed to show the same view of a file for the duration of the handle. For more information, seeAbout Transactional NTFS.

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

Examples

For a code example that shows you how to test for end-of-file, seeTesting for the End of a File. For other examples, seeCreating and Using a Temporary File andOpening a File for Reading or Writing.

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

File Management Functions

GetCommTimeouts

GetOverlappedResult

GetQueuedCompletionStatus

OVERLAPPED

PeekNamedPipe

ReadFileEx

SetCommTimeouts

SetErrorMode

WriteFile


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo