ReadFile Function
Reads data from a file or overlapping object.
Syntax
BOOL ReadFile(
HANDLE hFile,
LPVOID lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead,
LPOVERLAPPED lpOverlapped
);
Parameters
| Parameter | Description |
|---|---|
hFile |
A handle to the file or I/O device (such as a pipe or communications resource) that is to be read. This handle must have been created by the CreateFile function with the GENERIC_READ access right. |
lpBuffer |
A pointer to the buffer that receives the data read from the file. |
nNumberOfBytesToRead |
The maximum number of bytes to be read. If this parameter is zero and the file is opened in non-overlapping mode, the function returns TRUE and zero bytes read. |
lpNumberOfBytesRead |
A pointer to a 32-bit variable that receives the number of bytes read by this function. If this parameter is NULL and hFile is a handle to a file, the function might fail and return FALSE. If this parameter is NULL and hFile is a handle to a pipe or communications resource, the function returns TRUE and zero bytes read. |
lpOverlapped |
A pointer to an OVERLAPPED structure that is required if the file handle is opened with FILE_FLAG_OVERLAPPED. For files opened with FILE_FLAG_OVERLAPPED, the offset in the OVERLAPPED structure is used to specify where to start reading data from the file. |
Return Value
| Value | Description |
|---|---|
TRUE |
The read operation completed successfully. If lpNumberOfBytesRead is not NULL, the value it contains indicates the actual number of bytes read. |
FALSE |
The function failed. To get extended error information, call GetLastError. |
Remarks
To read from a file, you must first create the file or open an existing file with the CreateFile function. The handle returned by CreateFile must be opened with the GENERIC_READ access right.
If lpOverlapped is NULL, the read operation starts at the current file position and is a blocking operation. The function does not return until the read operation has completed.
If lpOverlapped is not NULL, the read operation is a non-blocking operation. The file handle must have been opened with FILE_FLAG_OVERLAPPED. If the read operation cannot be completed immediately, ReadFile returns FALSE and GetLastError returns ERROR_IO_PENDING. The actual read operation occurs asynchronously.
When reading from a communications device, nNumberOfBytesToRead should be less than or equal to the size of the input buffer specified when the device was created.