[英]Can I read a dynamical length variable using fread without pointers?
I am using the cstdio (stdio.h)
to read and write data from binary files. 我正在使用cstdio (stdio.h)
从二进制文件读取和写入数据。 I have to use this library due to legacy code and it must be cross-platform compatible with Windows and Linux. 由于遗留代码,我必须使用此库,并且该库必须与Windows和Linux跨平台兼容。 I have a FILE* basefile_
which I use to read in the variables configLabelLength
and configLabel
, where configLabelLength
tells me how much memory to allocate for configLabel
. 我有一个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
Is there a way to read in configLabel
without using a pointer? 有没有一种方法可以在不使用指针的情况下读取configLabel
? For example is there a solution where I can use the c++ vector library or something where I do not have to worry about pointer memory management. 例如,有没有一种解决方案,我可以使用c ++矢量库,也可以不用担心指针内存管理。
Just do: 做就是了:
unsigned int configLabelLength; // 4 bytes*
fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_);
std::vector<char> configLabel(configLabelLength);
fread(&configLabel[0], 1, configLabel.size(), baseFile_);
The elements in a vector are contiguous. 向量中的元素是连续的。
* I assume you know that unsigned int
isn't necessary always 4 bytes. *我假设您知道unsigned int
不一定总是4个字节。 If you pay attention to your implementation details that's fine, but it'll be a bit easier if you adopt Boost's cstdint.hpp
and just use uint32_t
. 如果您注意实现细节,那很好,但是如果采用Boost的cstdint.hpp
并仅使用uint32_t
会更容易一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.