3. Implementation/Windows API

Testing for the End of a File

SSKK 2008. 11. 6. 08:50

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 following example test for the end of a file during a synchronous read operation.

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

// Check for eof
if (bResult &&  nBytesRead == 0, ) 
{
    // 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:

  • ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.
  • ReadFile returns FALSE and GetLastError returns ERROR_IO_PENDING.
  • GetOverlappedResult returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

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
    }
}

From : MSDN