定时仿真了一批数据报文,以二进制写入文件,将写入的文件再次打开,读取的数据与写入不一致。
以下为写入文件代码,写入文件的格式为一个报文ID infoid, 报文长度infolen, 报文数据区pinfodata:
//记录二进制输入
int CompRecog::WriteInMsgFile(int64_t infoid, int infolen, char*pinfodata)
{
QDateTime time = QDateTime::currentDateTime();
QString timestring = time.toString("yyyyMMdd_hhmmss");
QString shead = "zRcd";
QString stail = ".data";
QString file = shead + timestring + stail;
char* pfilename;
pfilename = file.toLatin1().data();
static FILE *pfile = NULL;
if(pfile == NULL)
{
pfile = fopen(pfilename, "w+b");
}
if(pfile != NULL)
{
int wr1 = fwrite(&infoid, sizeof(int64_t), 1, pfile);
int wr2 = fwrite(&infolen, sizeof(int), 1, pfile);
int wr3 = fwrite(&pinfodata, infolen, 1, pfile);
bool issucc = ((wr1 == 1) && (wr2 == 1) && (wr3 == 1));
if(issucc)
{
printf("write msg %llx of length %d in file \n", infoid, infolen);
printf("%x %x %x %x\n", pinfodata[0], pinfodata[1],pinfodata[2],pinfodata[3]);
}
fflush(pfile);
}
return 1;
}
以下为读取文件代码:
char filename[30] = "zRcd20220503_104606.data";
static FILE* pfile = NULL;
if(pfile == NULL)
{
pfile = fopen(filename, "r+b");
fseek(pfile, 0, SEEK_SET);
}
if((pfile != NULL) && (!feof(pfile)))
{
int64_t infoid;
int infolen;
char infodata[1024];
int bw1 = (fread(&infoid, sizeof(int64_t), 1, pfile));
int bw2 = (fread(&infolen, sizeof(int), 1, pfile));
int bw3 = (fread(infodata, infolen, 1, pfile));
bool succ = ((bw1 == 1) && (bw2 == 1) && (bw3 == 1));
if(succ)
{
printf("read msg %llx of length %d in file \n", infoid, infolen);
printf("%x %x %x %x \n", infodata[0], infodata[1], infodata[2], infodata[3]);
}
}
if(feof(pfile))
{
fclose(pfile);
}
数据写入文件端运行部分运行结果:
write msg 6080b01 of length 27 in file
1 0 0 0
接收一次融合信息
CompRecog :receiveInfo:infoid:0x6080b01, len:22, 2 0 0 0
write msg 6080b01 of length 22 in file
2 0 0 0
接收二次融合结构(有识别信息)
CompRecog :receiveInfo:infoid:0x6080b01, len:179, 3 0 0 0
write msg 6080b01 of length 179 in file
3 0 0 0
数据文件读取端部分运行结果:
read msg 6080b01 of length 22 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 179 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 27 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 22 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 179 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 27 in file
f4 c2 3f 78
send msg succ
read msg 6080b01 of length 22 in file
f4 c2 3f 78
我的数据是按周期产生写入文件的,写入完成后用另外一个程序读出来。在写入端的打印显示写入的报文ID是060801,报文长度有三种,分别是27,22,179,打印报文数据区的前四个字节分别显示为1,2,3。但是在读文件阶段,打印显示的报文ID和报文长度都对得上,但就是数据区前四个字节内容完全对不上,并且所有类型报文前四个字节都一样,这是怎么回事,希望各位提供思路