ReadFile() 读取的字节数少于其参数中的指定值
ReadFile() reads less bytes than the specified value in its argument
我有这个代码用于从串行端口读取字节,但对于客户端的设备,消息"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
...
使注释正确无误。
相关文章:
- 为什么我的变量存在于其范围之外
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- 使用类作为模板参数在其自身的延迟中
- 传递 std::array 参数,其大小限制为可扩展的大小集
- 如果 LTO 中的代码依赖于其构造的副作用,是否允许 LTO 删除未使用的全局对象?
- GCC 或 Clang 关于函数参数在其自己的默认参数中的范围内的名称是否正确?
- 以编程方式推断出枚举的大小,独立于其元素的价值
- 如何使用C++相对于其原始值更新 SQLite 行
- OOP设计:一个对象依赖于其所有依赖项的存在
- 如何指定模板参数是类模板,并从另一个模板参数推断其模板类型
- 我可以创建一个链接另一个库但不依赖于其include的c++库吗
- 类模板,独立于其参数的排列
- 相对于其数据在特定方向上移动的有效方法是什么
- 如果函数类型仅依赖于其自己的模板参数,则取决于函数类型
- 错误无法初始化 'int *' 类型的参数,其 rvalue 类型为 'int'
- 加载到内存的文件的大小远大于其磁盘大小?!!任何压缩方式
- 引用相对于其目标的生存期
- 使用"std::conditional_t"定义依赖于其模板参数的类"typedef"
- 通过引用传递字符串,并通过C++中的函数参数更新其值
- 非类型模板参数,其类型依赖于另一个参数