我有一个很奇怪的问题,我似乎无法弄清楚。不幸的是,我甚至不确定如何描述它,而没有描述我的整个应用程序。我想要做的是:sprintf()和WriteFile()影响字符串缓冲区
1) read a byte from the serial port 2) store each char into tagBuffer as they are read 3) run a query using tagBuffer to see what type of tag it is (book or shelf tag) 4) depending on the type of tag, output a series of bytes corresponding to the type of tag
我的大部分代码都实现了,我可以从串口发回正确的标签代码。但是我添加了两行作为调试语句,当我试图删除它们时,它们导致我的程序停止工作。
的线是在最下方的两行:
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
如果我试图删除它们,“tagBuffer”将只存储的最后一个字符为反对是一个缓冲。与下一行WriteFile()相同。
我认为sprintf和WriteFile是I/O函数,并且对变量没有影响。 我卡住了,我需要帮助来解决这个问题。
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if(strlen(tagBuffer) >= PACKET_LENGTH)
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if(str == "book")
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if (str == "shelf")
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
有了这两条线,我的输出是这样的: 小号SH她SHEL货架shelf0 shelf00的bookcode shelf0001
如果没有他们,我想通了,tagBuffer和BUF只保存最近的字符在任何时候。
任何帮助都将不胜感激。谢谢。
你在哪里以及如何定义tagBuffer? – 2008-11-09 07:59:57
char tagBuffer [8]; //保存标记ID int i = 0; // indexBuffer – Steve 2008-11-09 08:04:56