gpt4 book ai didi

C++(使用 的串行通信)- 我如何事先知道 ReadFile() 方法将读取多少个字符

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:45 24 4
gpt4 key购买 nike

ReadFile( hSerial , buffer , 25, &dwBytesRead , 0);

大家好

我的问题是如何在调用 ReadFile 之前找出我的 ReadFile 语句将返回多少个字符?我正在与之通信的设备根据发送的内容返回不同的数据。关于上面的 ReadFile,在那种情况下,我知道返回的数据长度为 25 个字符,但如果我不知道答案怎么办,我如何用一个足以接收任何数量数据的变量替换 25。

在我的代码中你会看到我有 2 个 Readfile 语句,在这两种情况下我都知道我将接收的数据量,我发送了一个固定的数字,当我不知道该数量时会发生什么?

#include "stdafx.h"
#include "windows.h"

BOOL SetCommDefaults(HANDLE hSerial);
void StripCRLFandPrint(char *command);

char buffer[1000];
HANDLE hSerial;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char trash;

int main(int argc, char* argv[])
{
hSerial = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0 , 0 , OPEN_EXISTING , 0 , 0);

if (hSerial == INVALID_HANDLE_VALUE) return GetLastError();

SetCommDefaults(hSerial);//Initializing the Device Control Block

COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;

char szRxChar[3];//varialble holds characters that will be sent
szRxChar[0] = '?';
DWORD y =0, z =0;
char buf[327];// will hold the data received

memset(buf,0,327);//initializing the buf[]
memset(buffer,0,10000);

WriteFile( hSerial , &szRxChar , 1, &dwBytesWritten ,0);
ReadFile( hSerial , buf , sizeof(buf), &dwBytesRead , 0);
printf("Retrieving data...\n\n");

//Displaying the buffer
printf( "%s",buf);

printf("\nData Read: %i\n",dwBytesRead);
printf("Enter an option:");
scanf("%c%c",&szRxChar,&trash);//Reading the next command to be sent

while(szRxChar[0] != '1')//Press one to exit
{
memset(buffer,0,10000);
//StripCRLFandPrint(szRxChar);
WriteFile( hSerial , &szRxChar, 1, &dwBytesWritten ,0);
ReadFile( hSerial , buffer , 25, &dwBytesRead , 0);

printf("%s",buffer);
printf("\nData Read: %i\n",dwBytesRead);
printf("\n");
printf("Enter an Option:");
scanf("%c%c",&szRxChar,&trash);
}

CloseHandle(hSerial);// Closing the handle

return 0;
}

最佳答案

您无法知道自己在要求什么,因为没有软件可以预测远程端的行为。因此,阅读应该在不同的线程中进行。在读取线程中,您可以指示 ReadFile 一次读取一个字节。您可以选择同时读取更多字节,但是您将冒着从另一部分收到完整消息但仍然没有收到通知的风险,因为 ReadFile 被阻塞等待更多数据。

自己创建线程代码可能具有挑战性。我建议您搜索已经为您处理此问题的库。

关于C++(使用 <windows.h> 的串行通信)- 我如何事先知道 ReadFile() 方法将读取多少个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662782/

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