繁体   English   中英

我可以使用没有指针的fread读取动态长度变量吗?

[英]Can I read a dynamical length variable using fread without pointers?

我正在使用cstdio (stdio.h)从二进制文件读取和写入数据。 由于遗留代码,我必须使用此库,并且该库必须与Windows和Linux跨平台兼容。 我有一个FILE* basefile_ ,用于读取变量configLabelLengthconfigLabel ,其中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.

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