Platform SDK: Files and I/O

Testing for the End of the File

The ReadFile function checks for the end-of-file condition (eof) differently for synchronous and asynchronous read operations. When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets the variable pointed to by lpNumberOfBytesRead to zero. An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile or during subsequent asynchronous operation.

The test for end-of-file during a synchronous read operation is simple, as shown in the following example:

// Attempt a synchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);

// Check for eof
if (bResult &&  nBytesRead == 0, ) 
{
    // We're at the end of the file
}

The test for end-of-file during an asynchronous read operation is more difficult. There are three end-of-file indicators for asynchronous read operations:

The following example shows how to test for an end-of-file during an asynchronous read operation:

// Attempt to initiate an asynchronous read operation.
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);

// Check if there was a problem.
if (!bResult) 
{
    switch (dwError = GetLastError()) 
    {
        case ERROR_HANDLE_EOF: 
        // At the end of the file.
            break;
        case ERROR_IO_PENDING: 
        // I/O pending.
           break;
    }
}

// Check on an asynchronous read operation.
bResult = GetOverlappedResult(hFile, &gOverlapped, &nBytesRead, TRUE);

// Check if there was a problem.
if (!bResult) 
{
    switch (dwError = GetLastError()) 
    {
        case ERROR_HANDLE_EOF:
        // At the end of the file
    }
}