ReadFile() 读取的字节数少于其参数中的指定值

ReadFile() reads less bytes than the specified value in its argument

本文关键字:参数 于其 读取 字节数 ReadFile      更新时间:2023-10-16

我有这个代码用于从串行端口读取字节,但对于客户端的设备,消息"No enough information"显示,他说串行端口中有足够的信息,但是此消息 将显示。

int SuccessfulRead(unsigned char * s , DWORD bytesRead){
if( bytesRead == 2 ){
//...
return 1;
}
return 0;
}
//Reading
int i=1 , breakWhile=0 ;
while(!breakWhile)
{
DWORD dwRead;
BOOL fWaitingOnRead = FALSE; //overlapped
OVERLAPPED osReader = {0};
unsigned char lpBuf[2];
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL){
MessageBox( NULL , L"Unable to create event" , L"Error" , MB_OK);
breakWhile=1;
}
if (!fWaitingOnRead) {
// Issue read operation.
if (!ReadFile(hPort2, lpBuf, 2, &dwRead,&osReader)) {
if (GetLastError() != ERROR_IO_PENDING){     
MessageBox(NULL , L"Error in communication" , L"ERROR" , MB_OK);
break;
}
else
fWaitingOnRead = TRUE;
}
else {
// read completed immediately
int res=SuccessfulRead(lpBuf,dwRead);
if( !res){
MessageBox(NULL , L"No enough information" , L"" , MB_OK);
break;
}
}
}

#define READ_TIMEOUT   2000      // milliseconds
DWORD dwRes=0;
if (fWaitingOnRead) {
dwRes = WaitForSingleObject(osReader.hEvent,READ_TIMEOUT);
switch(dwRes)
{
// Read completed.
case WAIT_OBJECT_0:{
if (!GetOverlappedResult(hPort2, &osReader, &dwRead,FALSE))
MessageBox(NULL , L"Error in GetOverlappedResult" , L"Error" , MB_OK);
else{
// Read completed successfully.
int res=SuccessfulRead(lpBuf,dwRead);
if(!res){//less than two bytes read that is one byte readed
MessageBox(NULL , L"No enough information" , L"" , MB_OK);
breakWhile=1;//exit loop
}
//Reset flag so that another opertion can be issued.
fWaitingOnRead = FALSE;
}
break;
case WAIT_TIMEOUT:
if( i==1){//failed in first try
MessageBox(NULL , L"There is no data please try again", L"" , MB_OK);
}

breakWhile=1;//exit loop
break;
}
}
}
CloseHandle(osReader.hEvent);
i++;
}

由于ReadFile(hPort2, lpBuf, 2, &dwRead,&osReader),它每次必须读取 2 个字节,但它第一次读取 1 个字节,因此这意味着串行端口中不超过 1 个字节。 但似乎code vision读取该字节,为什么该程序在超过 1 个字节时只读取 2 个字节?当以ReadFile()为单位时,要读取的字节为 2。

为什么它不起作用以及如何使其工作?

它能与timeout价值有关吗?

谢谢

在这里:

int res=SuccessfulRead(lpBuf,dwRead);
if(!res){//less than two bytes read that is one byte readed

注释表明您期望>= 两个字节,但SuccessfulRead()只在读取两个字节时才返回非零:

if( bytesRead == 2 ){ // EXACTLY two bytes!!!
//...
return 1;
}

你需要:

if( bytesRead <= 2 ){ // AT LEAST two bytes
...

使注释正确无误。