c语言中ERROR_SUCCESS,c – ReadFile()表示失败,但错误代码为ERROR_...

在Windows环境下,使用C语言通过ReadFile()函数从串口COM3读取数据时遇到问题。ReadFile()返回false表明读取失败,但调用GetLastError()获取错误代码时返回的是ERROR_SUCCESS(0),使得错误排查困难。代码中包含了创建串口、设置波特率、数据位、停止位和流控制以及设置超时的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在Windows上使用ReadFile()从串口读取数据.这个代码在某个时间点工作正常,但它现在失败了,我试图找出问题的根源,所以我怀疑它是串行配置或超时的问题,因为这些都没有改变.

ReadFile()返回false,表示发生了错误.但是,当我立即检查GetLastError()的值时,它返回0,即ERROR_SUCCESS.读取的字节数是0,所以我倾向于认为确实出现了问题,但错误代码完全没用.

有任何想法吗?谢谢.

编辑:这是一些相关的代码片段:

#define GPS_COM_PORT L"COM3"

// for reference, the device communicates at 115200 baud,

// no parity, 1 stop bit, no flow control

// open gps com port

hGpsUart = CreateFile(GPS_COM_PORT, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

if (hGpsUart == INVALID_HANDLE_VALUE)

{

if (GetLastError() == ERROR_FILE_NOT_FOUND)

{

msg.setText("GPS COM port does not exist!");

msg.exec();

QApplication::quit();

}

msg.setText("Error occurred while trying to open GPS COM port!");

msg.exec();

QApplication::quit();

}

// set gps com port settings

dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

if (!GetCommState(hGpsUart, &dcbSerialParams))

{

msg.setText("Could not get GPS COM port settings!");

msg.exec();

QApplication::quit();

}

dcbSerialParams.BaudRate = CBR_115200;

dcbSerialParams.ByteSize = 8;

dcbSerialParams.StopBits = ONESTOPBIT;

dcbSerialParams.Parity = NOPARITY;

if (!SetCommState(hGpsUart, &dcbSerialParams))

{

msg.setText("Could not set GPS COM port settings!");

msg.exec();

QApplication::quit();

}

// set gps com port timeouts

timeouts.ReadIntervalTimeout = MAXDWORD;

timeouts.ReadTotalTimeoutConstant = 0;

timeouts.ReadTotalTimeoutMultiplier = 0;

timeouts.WriteTotalTimeoutConstant = 50;

timeouts.WriteTotalTimeoutMultiplier = 10;

if (!SetCommTimeouts(hGpsUart, &timeouts))

{

msg.setText("Could not set GPS COM port timeouts!");

msg.exec();

QApplication::quit();

}

// ... later in the code ...

char buf[161] = {0};

DWORD bytes_read = 0;

// This returns false...

if (!ReadFile(hGpsUart, buf, 160, &bytes_read, NULL))

{

// Yet in here, GetLastError() returns ERROR_SUCCESS (0)

QMessageBox msg;

msg.setText("Error reading from GPS UART!");

msg.exec();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值