gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:00:30 27 4
gpt4 key购买 nike

我有这段代码用于从串行端口读取字节,但对于客户端设备,消息 "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++;
}

每次必须读取 2 个字节,因为 ReadFile(hPort2, lpBuf, 2, &dwRead,&osReader) ,但是第一次读取的是1个字节,所以说明串口中的数据不超过1个字节。但似乎code vision读取该字节,为什么当超过 2 个字节时该程序只读取 1 个字节?当在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
...

确保评论正确。

关于c++ - ReadFile() 读取的字节数少于其参数中指定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com