繁体   English   中英

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

[英]How to read x characters from position y in a char * buffer?

我正在读取缓冲区(char *),并且有一个游标,在其中跟踪缓冲区的起始位置,是否有办法将7-64个字符复制出缓冲区,还是我最好的选择是循环播放从位置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;

}

将指针移动到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个字节之后,我们在第58个索引处添加了空字符:

/* 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 ++ 字符串库std::string类。 然后,您可以在string实例上调用substr substring方法来获取感兴趣的57个字符的子字符串。 它将减少头痛,并减少重新发明轮子的时间。

但是以上代码对于C和C ++应用程序都应该有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM