File Management Functions


ReadFile Function

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, see ReadFileEx.

Syntax

C++
BOOL WINAPI ReadFile(
  __in         HANDLE hFile,
  __out        LPVOID lpBuffer,
  __in         DWORD nNumberOfBytesToRead,
  __out_opt    LPDWORD lpNumberOfBytesRead,
  __inout_opt  LPOVERLAPPED lpOverlapped
);

Parameters

hFile [in]

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

For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept function.

lpBuffer [out]

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.

nNumberOfBytesToRead [in]

The maximum number of bytes to be read.

lpNumberOfBytesRead [out, optional]

A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile 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 [in, out, optional]

A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL.

If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.

For an hFile 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 the Offset and OffsetHigh members of the OVERLAPPED structure. For an hFile that does not support byte offsets, Offset and OffsetHigh are ignored.

For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the Synchronization 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 the GetLastError function.

Note  The GetLastError code ERROR_IO_PENDING is not a failure; it designates the read operation is pending completion asynchronously. For more information, see Remarks.

Remarks

The ReadFile 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.

If the ReadFile function attempts to read past the end of the file, the function returns zero, and GetLastError returns ERROR_HANDLE_EOF.

The ReadFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_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.

Use CancelSynchronousIo to cancel pending synchronous I/O operations.

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

The ReadFile function may fail with ERROR_NOT_ENOUGH_QUOTA, which means the calling process's buffer could not be page-locked. For additional information, see SetProcessWorkingSetSize.

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 the Synchronization and File Position section and in the CreateFile reference topic.

Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of the ReadFile function. By default, the console mode is ENABLE_LINE_INPUT, which indicates that ReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, but GetLastError returns ERROR_OPERATION_ABORTED. For more information, see CreateFile.

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

If ReadFile attempts to read from a mailslot that has a buffer that is too small, the function returns FALSE and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

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

If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:

  • The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.
  • The lpNumberOfBytesRead parameter should be set to NULL. Use the GetOverlappedResult function to get the actual number of bytes read. If the hFile parameter is associated with an I/O completion port, you can also get the number of bytes read by calling the GetQueuedCompletionStatus function.

Synchronization and File Position

If hFile is opened with FILE_FLAG_OVERLAPPED, it is an asynchronous file handle; otherwise it is synchronous. The rules for using the OVERLAPPED 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 as ReadFile using that handle generally return immediately, but can also behave synchronously with respect to blocked execution. For more information see http://support.microsoft.com/kb/156932.

Considerations for working with asynchronous file handles:

  • ReadFile may return before the read operation is complete. In this scenario, ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING, which allows the calling process to continue while the system completes the read operation.
  • The lpOverlapped parameter must not be NULL and should be used with the following facts in mind:

    • Although the event specified in the OVERLAPPED structure is set and reset automatically by the system, the offset that is specified in the OVERLAPPED structure is not automatically updated.
    • ReadFile resets the event to a nonsignaled state when it begins the I/O operation.
    • The event specified in the OVERLAPPED 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 the OVERLAPPED structure, and ReadFile 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 to GetOverlappedResult for that operation returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

Considerations for working with synchronous file handles:

  • If lpOverlapped is NULL, the read operation starts at the current file position and ReadFile does not return until the operation is complete, and the system updates the file pointer before ReadFile returns.
  • If lpOverlapped is not NULL, the read operation starts at the offset that is specified in the OVERLAPPED structure and ReadFile does not return until the read operation is complete. The system updates the OVERLAPPED offset before ReadFile returns.
  • When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero.

For more information, see CreateFile and Synchronous and Asynchronous I/O.

Pipes

If an anonymous pipe is being used and the write handle has been closed, when ReadFile attempts to read using the pipe's corresponding read handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.

If a named pipe is being read in message mode and the next message is longer than the nNumberOfBytesToRead parameter specifies, ReadFile returns FALSE and GetLastError returns ERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to the ReadFile or PeekNamedPipefunction.

If the lpNumberOfBytesRead parameter is zero when ReadFile returns TRUE on a pipe, the other end of the pipe called the WriteFile function with nNumberOfBytesToWrite set to zero.

For more information about pipes, see Pipes.

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, see About Transactional NTFS.

Examples

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

Requirements

Minimum supported clientWindows 2000 Professional
Minimum supported serverWindows 2000 Server
HeaderWinBase.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

Send comments about this topic to Microsoft

Build date: 11/12/2009

Tags : api


Community Content

Austin Donnelly MSFT
behavior when nNumberOfBytesToRead == 0

When ReadFile() is called with nNumberOfBytesToRead set to zero (0), it returns TRUE (success), sets *lpNumberOfBytesRead to 0, and GetLastError() return ERROR_SUCCESS; otherwise applications may have trouble telling this appart from the EOF condition.

Note that this is for a ReadFile to NTFS: ReadFile on a pipe might return 0 bytes read successfully if the other side of the pipe called WriteFile with 0 bytes.

Tags :

Doug Dumitru
lpNumberOfBytesRead not optional
In at least some cases, you cannot set this to NULL. The Fault is very low level and hard to catch with a debugger. The header definition should be changed to reflect this (or at least the bad cases defined). My error was on a regular NTFS file on Vista.
Tags :

wva
ERROR_HANDLE_EOF can be returned also on synchronous read
if lpOverlapped is not NULL and read is synchronous (positioned read , that uses lpOverlapped only to specify the offset), ReadFile at the end of file will return FALSE and GetLastError() will return ERROR_HANDLE_EOF.
Tags :

Alessandro Antonello
ERROR_HANDLE_EOF not returned
After installing the XP service pack 3 on a FAT32 file system the ReadFile() function does not return FALSE when I try to read past end of the file. nNumberOfBytesToRead is greater than zero and lpNumberOfBytesRead is set to zero when the function returns. But the function returns TRUE and GetLastError() returns ERROR_SUCCESS.
Tags :

Paul Baker
lpNumberOfBytesRead should be NULL if called asynchronously

It is important not to use lpNumberOfBytesRead if ReadFile() is called asynchronously.

The documentation for lpNumberOfBytesRead says "Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results".

The Remarks include this: "If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect: <...> The value returned in lpNumberOfBytesWritten is indeterminate". I believe that this is intended to refer to lpNumberOfBytesRead.

For example, I have a named pipe server on Windows XP SP2 reading a message from a pipe client in a separate process on the same machine. Sometimes, ReadFile() returns FALSE and GetLastError() returns ERROR_MORE_DATA. In this case, *lpNumberOfBytesRead is set to 0.

Presumably, one calls GetOverlappedResult() to obtain a reliable value for the number of bytes read. If ReadFile() returns FALSE and GetLastError() returns ERROR_IO_PENDING, the operation is pending. It is unclear in various pieces of documentation whether GetOverlappedResult() can be called if the operation is not pending. However, I would have to assume so since even if ReadFile() indicated that the operation is pending and GetOverlappedResult is called ASAP, it may be possible for it no longer to be pending.

UNCLEAR GetOverlappedResult() DOCUMENTATION 1:

GetOverlappedResult Function (Windows)
http://msdn.microsoft.com/en-us/library/ms683209.aspx

"The results reported by the GetOverlappedResult function are those of the specified handle's last overlapped operation to which the specified OVERLAPPED structure was provided, and for which the operation's results were pending."

The key phrase is "for which the operation's results were pending". What if the results were not pending?

UNCLEAR GetOverlappedResult() DOCUMENTATION 2:

Asynchronous Disk I/O Appears as Synchronous on Windows NT, Windows 2000, and Windows XP
http://support.microsoft.com/kb/156932

"Note that &NumberOfBytesRead passed into ReadFile is different from &NumberOfBytesTransferred passed into GetOverlappedResult. If an operation has been made asynchronous, then GetOverlappedResult is used to determine the actual number of bytes transferred in the operation after it has completed. The &NumberOfBytesRead passed into ReadFile is meaningless.

If, on the other hand, an operation is completed immediately, then &NumberOfBytesRead passed into ReadFile is valid for the number of bytes read. In this case, ignore the OVERLAPPED structure passed into ReadFile; do not use it with GetOverlappedResult or WaitForSingleObject".

The key phrase here is do not use it with GetOverlappedResult". Is that because it is not necessary? Or is it because it is unreliable to do so?

Tags :

Luis Bras
Returns TRUE for EOF on a syncronous read
When ReadFile attempts to read past the end of a file on a synchronous read operation, ReadFile returns TRUE and GetLastError() returns ERROR_SUCCESS, as stated on the article "Testing for the End of a File":
http://msdn.microsoft.com/en-us/library/aa365690%28VS.85%29.aspx

The information on the remarks section about this is only true for asynchronous read operations.
Tags :

Page view tracker