如何从char *缓冲区中的位置y读取x个字符?

时间:2012-10-07 02:56:02

标签: c++

我正在读缓冲区(char *)并且我有一个光标,我在那里跟踪我的缓冲区的起始位置,有没有办法将字符7-64复制出缓冲区,或者是我最好的选择只是将缓冲区从poistion x循环到位置y?

目标缓冲区的大小是另一个动态计算的函数的结果

初始化返回

variable-sized object 'version' may not be initialized

相关代码部分:

int32_t size = this->getObjectSizeForMarker(cursor, length, buffer);
cursor = cursor + 8; //advance cursor past marker and size
char version[size] = this->getObjectForSizeAndCursor(size, cursor, buffer);

-

char* FileReader::getObjectForSizeAndCursor(int32_t size, int cursor, char *buffer) {
  char destination[size];
  memcpy(destination, buffer + cursor, size);
}

-

int32_t FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
  //skip the marker and read next 4 byes
  cursor = cursor + 4; //skip marker and read 4
  unsigned char *ptr = (unsigned char *)buffer + cursor;
  int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
  return objSize;

}

1 个答案:

答案 0 :(得分:1)

将指针向前移动buffer六个单位(以获得第七个索引),然后将memcpy 64-7(57)个字节移动,例如:

const char *buffer = "foo bar baz...";
char destination[SOME_MAX_LENGTH];
memcpy(destination, buffer + 6, 64-7);

您可能希望终止destination数组,以便您可以使用标准C字符串函数来处理它。请注意,在复制的57个字节后,我们在 58th 索引处添加了空字符:

/* terminate the destination string at the 58th byte, if desired */
destination[64-7] = '\0'; 

如果您需要使用动态大小的destination,请使用指针而不是数组:

const char *buffer = "foo bar baz...";
char *destination = NULL;

/* note we do not multiply by sizeof(char), which is unnecessary */
/* we should cast the result, if we're in C++ */
destination = (char *) malloc(58); 

/* error checking */
if (!destination) { 
    fprintf(stderr, "ERROR: Could not allocate space for destination\n");
    return EXIT_FAILURE;
}

/* copy bytes and terminate */
memcpy(destination, buffer + 6, 57);
*(destination + 57) = '\0';
...

/* don't forget to free malloc'ed variables at the end of your program, to prevent memory leaks */
free(destination); 

老实说,如果您使用的是C ++,那么您应该使用C ++ strings librarystd::string类。然后,您可以在string实例上调用substr substring方法来获取感兴趣的57个字符的子字符串。这将减少头痛,减少重新发明轮子。

但是上面的代码对C和C ++应用程序都很有用。