我可以使用 fread 而不使用指针读取动态长度变量吗?

发布于 2024-09-09 17:44:38 字数 766 浏览 6 评论 0原文

我正在使用 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++ 矢量库或其他我不必担心指针内存管理的解决方案。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偷得浮生 2024-09-16 17:44:38

就这样做:

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,则会更容易一些。

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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文