c++ cli从文件中比较十六进制字节不工作

c++ cli comparing hexadecimal bytes from a file not working

本文关键字:十六进制 字节 工作 比较 cli 文件 c++      更新时间:2023-10-16

我有一个名为ab.exe的文件它包含了这个十六进制

0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 bbaae8cafdffff83c408000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000054年aae8cafdffff83c40800000000000000000000000000000000000000000000000000000000000000000000000000aae8cafdffff83c4088d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

我在c++中有这个代码,它应该检测十六进制字符串是否在文件中,如果它是将它添加到列表框中。

array<Byte>^ target1 = { 0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08,0x8D };
array<Byte>^ target2 = { 0x54,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };
array<Byte>^ target3 = { 0xBB,0xAA,0xE8,0xCA,0xFD,0xFF,0xFF,0x83,0xC4,0x08 };

int matched1 = 0;
int matched2 = 0;
int matched3 = 0;
FileStream^ fs2 = gcnew FileStream(line, FileMode::Open, FileAccess::Read, FileShare::ReadWrite);
int value;
do
{
    value = fs2->ReadByte();
    if (value == target1[matched1]) {
        matched1++;
    }
    else
        matched1 = 0;
    if (value == target2[matched2]) {
        matched2++;
    }
    else
        matched2 = 0;
    if (value == target3[matched3]) {
        matched3++;
    }
    else
        matched3 = 0;
    if(matched1 == target1->Length)
    {
        listBox1->Items->Add(line + "1");
    }
    if(matched2 == target2->Length)
    {
        listBox1->Items->Add(line + "2");
    }
    if(matched3 == target3->Length)
    {
        listBox1->Items->Add(line + "3");
    }
} while (value != -1);
fs2->Close();

问题是它只将+ 3行添加到列表框中,而不将+ 1行或+ 2行添加到列表框

我不知道为什么,因为所有3个字符串都在文件中,所以它们都应该添加到列表框中。由于某种原因,只有最后一个被加了因为我试着只加2,第二个被加了。有人能告诉我为什么他们没有全部被添加到列表框。由于

Update1

在对

进行更多操作之后,它不是每次添加的最后一个目标,而是出现在被添加的文件中的第一个字符串。我使用消息框逐步完成程序,正在发生的事情是,让我们说54AAE8CAFDFFFF83C408是出现在文件中的第一个字符串,然后将添加行+ 2,但是由于某种原因,所有3个匹配的整数停止计数,它们只是= 0文件的其余部分。谁能给我解释一下这是为什么以及如何解决它?

更新2

这就是问题的答案。我只需要添加一个matched = 0;在每个添加到列表框命令后。

listBox1->Items->Add(line + "1");
matched1 = 0;
listBox1->Items->Add(line + "2");
matched2 = 0;
listBox1->Items->Add(line + "3");
matched3 = 0;

在我看来,在一个模式(这里是target3)的第一次匹配之后,您读取了target3的最后一个字节(因为matched3++),这可能会导致不希望的行为。

Update1:

if(matched1 == target1->Length)
{
  matched1 = 0; // pattern matched so reset counter
  ...
}