串口程序 同步 读操作 请教readfile 什么时候返回 true 什么时候返回false?
我的VC6的readfile返回 怎么不稳(有时1 有时0 ,相同条件下)while(ReadFile(h,(LPVOID)buf,sizeof(buf),(LPDWORD)&NumberOfBytesRead,NULL))
{
break
}
 m_strRXData.Format("%x",*buf);
 UpdateData(FALSE);谢谢

解决方案 »

  1.   

    看MSDN吧,说的很清楚:
    ReadFileThe ReadFile function reads data from a file, starting at the position indicated by the file pointer. After the read operation has been completed, the file pointer is adjusted by the number of bytes actually read, unless the file handle is created with the overlapped attribute. If the file handle is created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the read operation.This function is designed for both synchronous and asynchronous operation. The ReadFileEx function is designed solely for asynchronous operation. It lets an application perform other processing during a file read operation.
    BOOL ReadFile(
      HANDLE hFile,
      LPVOID lpBuffer,
      DWORD nNumberOfBytesToRead,
      LPDWORD lpNumberOfBytesRead,
      LPOVERLAPPED lpOverlapped
    );
    Return Values
    The ReadFile function returns when one of the following conditions is met: a write operation completes on the write end of the pipe, the number of bytes requested has been read, or an error occurs.If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError.If the return value is nonzero and the number of bytes read is zero, the file pointer was beyond the current end of the file at the time of the read operation. However, if the file was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the return value is zero and GetLastError returns ERROR_HANDLE_EOF when the file pointer goes beyond the current end of file.
      

  2.   

    If the function succeeds, the return value is nonzero.If the function fails, the return value is zero. To get extended error information, call GetLastError.如果函数执行成功,返回非零值。如果函数执行失败,返回零。可以调用GetLastError,获得更详细的错误信息。
      

  3.   

    以前在网上看过一篇文章说,在win2000上,readfile是一直返回TRUE的,现在觉得纯粹是谬论。
    在前段时间刚好有机会接触串口。我实现的是异步重叠方式读写串口。当时发现:
    readfile在前台操作(主窗口在前面),返回的是TRUE,后台(主窗口在后面)返回的是false。所以你需要处理readfile是false的情况
    unsigned long hasread = 0;
    if (!readfile(hHandle, buf, size, &hasread, &over))
    {
         if (GetLastError()==ERROR_IO_PENDING)
         {
             while(!GetOverlappedResult(hHandle, &over, &hasread, true))
             {
                  if (GetLastError() == ERROR_IO_INCOMPLETE)
                      continue;
             }
         }
         else
             return false;
    }
    else if (HasRead != (unsigned long)size) 
    {
        return false;
    }
    return true;