WinAPI ReadFile中的 lpNumberOfBytesRead 错误!!
各位高手,小弟在用ReadFile读取串口时,参数lpNumberOfBytesRead的值和实际得到的字符串长度不相等,代码如下:
fReadStat=ReadFile(PortHandle, ComBytes, ComStat.cbInQue, &dwByteRead, &osRead);
//ComBytes 为接受数组的首地址;
//ComStat.cbInQue为要读取的字节数
//dwByteRead为实际读到的字节数
ASSERT(ComStat.cbInQue==dwByteRead);会出错,但并不是每一次都出错。随机性的出错。因为
串口收到的字节数每次都不同,dwByteRead经常为以前某一次的值。但是ComBytes处接收的字符串
正确,且长度与ComStat.cbInQue的值相等。而且我每次都把串口缓冲区清空。
PurgeComm(PortHandle,PURGE_RXCLEAR);
我不知道 ReadFile我是不是有什么地方用的不对,请高手帮忙啊!!
不胜感激!!!!
[解决办法]
// 异步方式,ReadFile会立即返回,fReadStat都是false吧?
[解决办法]
int nWantToReadBytes = ComStat.cbInQue;
int nHaveBeenReadBytes = 0
LPBYTE lpB = ComBytes;
while (nWantToReadBytes>= 0)
{
fReadStat=ReadFile(PortHandle, ComBytes + nHaveBeenReadBytes, nWantToReadBytes, &dwByteRead, &osRead);
nWantToReadBytes -= dwByteRead;
nHaveBeenReadBytes += dwByteRead;
}