0

我正在尝试在给定文件中查找一个字符串(实际上该文件是 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 文件。为什么它不访问它?有任何想法吗 ??*

请给出实现它的替代方案..我确定我尝试的方法行不通..

4

2 回答 2

2

AC 样式字符串是由零字符终止的字符数(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;
}
于 2013-07-26T13:43:31.077 回答
0

如果你真的想使用,strstr那么你需要用 .转义缓冲区中包含的字符串'\0'。如果您知道放入缓冲区的数据大小(比方说,sizeOfData),那么您可以在使用之前执行以下操作strstr

buffer[sizeOfData] = '\0';

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

于 2013-07-26T13:49:34.900 回答