如何在两个文本文件中计算不同的数据包编号

How to count the different packet number in two text file

本文关键字:计算 编号 数据包 文件 文本 两个      更新时间:2023-10-16

我有两个文本文件in.textout.text。我将将它们读入unsigned char **,其中数组的每个元素存储长度为 T=32 的数据作为波纹管代码

char *filename = "in.text";
FILE *stream;
int numPackets = 10;
int T = 32; // Length of each packets
unsigned char **PacketsIn;
fopen_s(&stream, filename, "rb");   
fseek(stream, 0, SEEK_SET);
for (int i = 0; i < numPackets; i++) {      
    fread(PacketsIn[i], 1, T, stream);      
}
fclose(stream);

以同样的方式,我可以使用上面的代码获得PacketsOut

filename = "out.text";
FILE *streamout;
numPackets = 10;
T = 32; // Length of each packets
unsigned char **PacketsOut;
fopen_s(&streamout, filename, "rb");    
fseek(streamout, 0, SEEK_SET);
for (int i = 0; i < numPackets; i++) {      
    fread(PacketsOut[i], 1, T, streamout);      
}
fclose(streamout);

我想计算 PacketsInPacketOut 中有多少个不同的数据包(每个数据包都有 10 个数据包,我们将比较 PacketsIn 中的第一个数据包和 PacketsOut 中的第一个数据包。如果它们不同,则计数增加 1)。你能帮我解决吗

这就是我尝试过的

int count = 0;
for (int i = 0; i < numPackets; i++) {      
    if (PacketsIn[i] != PacketsOut[i])
       count++; 
}

数据包是字节数组,您必须为这些数组分配内存,作为自动存储、函数本地存储或带有 malloc 的堆。 此外,您不能将数组与==!=进行比较,您需要使用执行逐字节比较的函数。 在 <string.h> 中声明memcmp执行此操作,如果数组不同,则返回非 0 值。

这是更正后的版本:

#include <string.h>
int compare_packets(void) {
    FILE *stream;
    int numPackets = 10;
    int T = 32; // Length of each packet
    unsigned char PacketsIn[numPackets][T];
    unsigned char PacketsOut[numPackets][T];
    fopen_s(&stream, "in.text", "rb");   
    for (int i = 0; i < numPackets; i++) {      
        fread(PacketsIn[i], 1, T, stream);      
    }
    fclose(stream);
    fopen_s(&stream, "out.text", "rb");    
    for (int i = 0; i < numPackets; i++) {      
        fread(PacketsOut[i], 1, T, stream);      
    }
    fclose(stream);
    int count = 0;
    for (int i = 0; i < numPackets; i++) {      
        if (memcmp(PacketsIn[i], PacketsOut[i], T)
            count++; 
    }
    return count;
}

当 memcmp 返回非零值时,这表示两个给定字符串之间的差异:

#include <string.h>
if (memcmp(PacketsIn[i],PacketsOut[i],32)!=0)
   count++