0

基本上我有一个缓冲区,我在其中寻找各种标志来从二进制文件格式中读取某些字段。我已将文件读入缓冲区,但是当我开始编写代码以在缓冲区中搜索标志时,我立即碰壁了。我是 C++ 菜鸟,但这是我所拥有的:

void FileReader::parseBuffer(char * buffer, int length)
{
  //start by looking for a vrsn
  //Header seek around for a vrns followed by 32 bit size descriptor
  //read 32 bits at a time
  int cursor = 0;
  char vrsn[4] = {'v','r','s','n'};
  cursor = this->searchForMarker(cursor, length, vrsn, buffer);
}

int FileReader::searchForMarker(int startPos, int eof, char marker[], char * buffer)
{
  int cursor = startPos;
  while(cursor < eof) {
    //read ahead 4 bytes from the cursor into a tmpbuffer
    char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]}; 
    if (strcmp(marker, tmpbuffer)) {
      cout << "Found: " << tmpbuffer;
      return cursor;
    }
    else {
      cout << "Didn't Find Value: " << marker << " != " << tmpbuffer;
    }
    cursor = cursor + 4;
  }
}

我的标题如下所示:

#ifndef __FILEREADER_H_INCLUDED__
#define __FILEREADER_H_INCLUDED__

#include <iostream>
#include <fstream>
#include <sys/stat.h>



class FileReader {
  public:
    FileReader();
    ~FileReader();
    int open(char *);
    int getcode();
  private:
    void parseBuffer(char *, int);
    int searchForMarker(int, int, char[], char *);
    char *buffer;
};

#endif

我希望用 strcmp 找回与 vrsn 的匹配,但我的结果看起来像这样

Didn't Find Value: vrsn != vrsn
Found: 

看起来它在通过我正在寻找的 char 数组后的第二遍中找到了它。

相关十六进制码

十六进制

4

3 回答 3

3

您的问题有两个方面:

  1. strcmp成功时返回“0”,而不是失败时。阅读文档。

  2. strcmp需要以 null 结尾的字符串。您说您选择了非终止char数组,因为这是您的数据库库使用的。好吧,好吧。但是,您仍然违反strcmp. 改为使用strncmp(它需要一个长度参数),或者最好实际编写 C++并开始使用std::vector<char>和朋友。

于 2012-10-07T01:31:54.853 回答
0

Shouldn't that be something like int FileReader::searchForMarker(...) { .... }?

For the second query, I guess the strcmp works when it has two null terminated strings as its arguments. For example str1[]="AAA"; and str2[]="AAA"; then strcmp() would be used as if(strcmp(str1,str2)==0) which will return 0 to indicate that they are equal. In your case, the tmpbuffer that you have created is not a null terminated string unless you add \0 in the end.So you might want to add \0 in the end of your tmpbuffer to create a string of 'v' 'r' 'n' 's'.

于 2012-10-07T01:06:38.693 回答
0
char vrsn[4] = {'v','r','s','n'};

仅包含指定的 4 个字符。最后没有空字符的空间。

 char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};

仅包含缓冲区中的 4 个字符。最后没有空字符的空间。

最终你打电话:

if (strcmp(marker, tmpbuffer)) {

strcmp() 函数期望它的每个参数都以空字符 ('\0') 结尾。它想使用以空结尾的字符串。

由于您的数据不是以空值结尾的,因此您可能希望使用 memcmp() 而不是 strcmp()。

此外,当 strcmp() 的参数相等时,它返回零,因此 if 语句中的条件被反转。(零为假,其他一切为真。) memcmp() 函数在其参数相等时也将返回零。

于 2012-10-07T01:21:38.170 回答