Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Setup File Download EaseFilter Monitor, Control and Encryption Filter Driver SDK Zip File
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.
BOOL ReadFile( HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped );
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).
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 CreateFilefunction, or a socket handle returned by the socket or accept function.
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.
nNumberOfBytesToRead
The maximum number of bytes to be read.
lpNumberOfBytesRead
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
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 OVERLAPPEDstructure, 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 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 ReadFile function returns when one of the following conditions occur:
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:
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 CreateFilereference 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 thatReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, but GetLastError returnsERROR_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 returnsERROR_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:
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 WriteFilefunction with nNumberOfBytesToWrite set to zero.
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);
The following example uses CreateFile to open an existing file for reading and ReadFile to read up to 80 characters synchronously from the file.
In this case, CreateFile succeeds only if the specified file already exists in the current directory. A subsequent call to open this file with CreateFile will succeed if the call uses the same access and sharing modes.
Tip: You can use the file you created with the previous WriteFile example to test this example.
#include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe.h> #define BUFFERSIZE 5 DWORD g_BytesTransferred = 0; void DisplayError(LPTSTR lpszFunction); VOID CALLBACK FileIOCompletionRoutine( __in DWORD dwErrorCode, __in DWORD dwNumberOfBytesTransfered, __in LPOVERLAPPED lpOverlapped ); VOID CALLBACK FileIOCompletionRoutine( __in DWORD dwErrorCode, __in DWORD dwNumberOfBytesTransfered, __in LPOVERLAPPED lpOverlapped ) { _tprintf(TEXT("Error code:\t%x\n"), dwErrorCode); _tprintf(TEXT("Number of bytes:\t%x\n"), dwNumberOfBytesTransfered); g_BytesTransferred = dwNumberOfBytesTransfered; } // // Note: this simplified sample assumes the file to read is an ANSI text file // only for the purposes of output to the screen. CreateFile and ReadFile // do not use parameters to differentiate between text and binary file types. // void __cdecl _tmain(int argc, TCHAR *argv[]) { HANDLE hFile; DWORD dwBytesRead = 0; char ReadBuffer[BUFFERSIZE] = {0}; OVERLAPPED ol = {0}; printf("\n"); if( argc != 2 ) { printf("Usage Error: Incorrect number of arguments\n\n"); _tprintf(TEXT("Usage:\n\t%s\n"), argv[0]); return; } hFile = CreateFile(argv[1], // file to open GENERIC_READ, // open for reading FILE_SHARE_READ, // share for reading NULL, // default security OPEN_EXISTING, // existing file only FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file NULL); // no attr. template if (hFile == INVALID_HANDLE_VALUE) { DisplayError(TEXT("CreateFile")); _tprintf(TEXT("Terminal failure: unable to open file \"%s\" for read.\n"), argv[1]); return; } // Read one character less than the buffer size to save room for // the terminating NULL character. if( FALSE == ReadFileEx(hFile, ReadBuffer, BUFFERSIZE-1, &ol, FileIOCompletionRoutine) ) { DisplayError(TEXT("ReadFile")); printf("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError()); CloseHandle(hFile); return; } SleepEx(5000, TRUE); dwBytesRead = g_BytesTransferred; // This is the section of code that assumes the file is ANSI text. // Modify this block for other data types if needed. if (dwBytesRead > 0 && dwBytesRead <= BUFFERSIZE-1) { ReadBuffer[dwBytesRead]='\0'; // NULL character _tprintf(TEXT("Data read from %s (%d bytes): \n"), argv[1], dwBytesRead); printf("%s\n", ReadBuffer); } else if (dwBytesRead == 0) { _tprintf(TEXT("No data read from file %s\n"), argv[1]); } else { printf("\n ** Unexpected value for dwBytesRead ** \n"); } // It is always good practice to close the open file handles even though // the app will exit here and clean up open handles anyway. 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); }