strstr无法搜索八进制格式数据中的字符串

strstr not able to search the string inside the data in octal format

本文关键字:数据 字符串 格式 八进制 搜索 strstr      更新时间:2023-10-16

我试图在给定的文件中找到一个字符串(实际上这个文件是tar文件(请注意这里),我在notepad++中打开了这个文件,并从打开的文件中随机提取了一个字符串),我将完整的tar文件存储在缓冲区中,现在我想在存储的缓冲区中找到我使用strstr函数复制的字符串的位置。

要做的代码是这样的(这是绝对正确的)-

char *compare= "_.png"; //suppose this is the copied string
//which is to be find out in buffer using strstr
            char * StartPosition;
            StartPosition = strstr (buffer,compare);
            __int64 count=0; 
            MessageBox(m_hwndPreview,L"before the while loop",L"BTN WND6",MB_ICONINFORMATION);
            while (StartPosition!=NULL)
            {
                MessageBox(m_hwndPreview,L"hurr inside the while loop",L"BTN WND6",MB_ICONINFORMATION);
                MessageBoxA(m_hwndPreview,strerror(errno),"BTN WND4", MB_ICONINFORMATION);
                count=StartPosition-buffer+1;
                return 0;
            }

假设我在记事本中有tar文件的内容,如下所示,我从比较-中复制了这个字符串

3_VehicleWithKinematicsAndAerodynamics_.000.png  IHDR (here is some strange data which can't be copied and also there are lot of NULL but we have to find out the position of "_.png" so not so difficult in this case ).

问题是,我的代码运行良好,直到我将数据存储在.png之前,然后我才能使用strstr找到它的位置。问题是,当我试图找出之后出现的字符串位置时

`3_VehicleWithKinematicsAndAerodynamics_.000.png  IHDR ...suppose here we have strange data (which is data block if we see the tar parser)...after this we have another file  like..."3_VehicleWithKinematicsAndAerodynamics_.html"`

如果我想用strstr找到这个"3_VehicleWithKinematicsAndAerodynamics_.html",那么由于它们之间的奇怪数据,我找不到它。(因为我认为编译器无法识别这些数据,因此我无法访问位于奇怪数据之后的文件)为了更清楚地看到文件在tar文件中的位置如下-

3_VehicleWithKinematicsAndAerodynamics_.000.png  IHDR ............(its data blocl-which is strange contents if you open in tar file)....3_VehicleWithKinematicsAndAerodynamics_.000.html

我必须使用strstr访问.html文件。为什么它没有访问它??有什么想法吗

请给出实现它的替代方案。我确信我所尝试的不会奏效。。

C风格字符串是以零字符(NUL字符-值为零,而不是字符"0")结尾的字符数。这意味着strstr一旦命中这样的字节就会停止。

一个非常合理的解决方案是简单地编写一个函数,根据二进制数据的长度而不是"终止字符"来搜索二进制数据。

类似的东西(这仍然假设str是一个C风格的字符串):

 char *find_str_in_data(const char *str, const char *data, int length)
 {
    int pos = 0;
    int slen = strlen(str);
    while(pos < length-slen)
    {
       int i = 0;
       while(i < slen && str[i] = data[pos+i])
       {
           i++;
       }
       if (i == slen)
          return data + pos;
   }
   return NULL;
}

如果您真的想使用strstr,那么您需要''转义缓冲区中包含的字符串。如果您知道放入缓冲区的数据的大小(比如sizeOfData),那么在使用strstr:之前,您可以这样做

buffer[sizeOfData] = '';

警告:如果sizeOfData等于缓冲区的大小,那么您将需要更大的缓冲区,或者用''覆盖最后一个字符(在第二种情况下,您应该手动检查缓冲区尾部,因为您覆盖的字符可能是您要查找的序列中的一个字符)。