我可以使用 fread 而不使用指针读取动态长度变量吗?
我正在使用 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++ 矢量库或其他我不必担心指针内存管理的解决方案。
I am using the cstdio (stdio.h)
to read and write data from binary files. I have to use this library due to legacy code and it must be cross-platform compatible with Windows and 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
.
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? 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就这样做:
向量中的元素是连续的。
* 我假设您知道
unsigned int
不一定总是4 个字节。如果您注意实现细节,那没问题,但如果您采用 Boost 的cstdint.hpp
并仅使用uint32_t
,则会更容易一些。Just do:
The elements in a vector are contiguous.
* I assume you know that
unsigned int
isn't necessary always 4 bytes. If you pay attention to your implementation details that's fine, but it'll be a bit easier if you adopt Boost'scstdint.hpp
and just useuint32_t
.