简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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