[英]Can I read a dynamical length variable using fread without pointers?
我正在使用cstdio (stdio.h)
从二进制文件读取和写入数据。 由于遗留代码,我必须使用此库,并且该库必须与Windows和Linux跨平台兼容。 我有一个FILE* basefile_
,用于读取变量configLabelLength
和configLabel
,其中configLabelLength
告诉我要为configLabel
分配多少内存。
unsigned int configLabelLength; // 4 bytes
char* configLabel = 0; // Variable length
fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_);
configLabel = new char[configLabelLength];
fread(configLabel,1, configLabelLength,baseFile_);
delete [] configLabel; // Free memory allocated for char array
configLabel = 0; // Be sure the deallocated memory isn't used
有没有一种方法可以在不使用指针的情况下读取configLabel
? 例如,有没有一种解决方案,我可以使用c ++矢量库,也可以不用担心指针内存管理。
做就是了:
unsigned int configLabelLength; // 4 bytes*
fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_);
std::vector<char> configLabel(configLabelLength);
fread(&configLabel[0], 1, configLabel.size(), baseFile_);
向量中的元素是连续的。
*我假设您知道unsigned int
不一定总是4个字节。 如果您注意实现细节,那很好,但是如果采用Boost的cstdint.hpp
并仅使用uint32_t
会更容易一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.