简体   繁体   中英

reading from a binary file in a length indicator way in C++

How can I properly read from a binary file in a length indicator way? I'm doing something like this but it keeps giving me weird results:

size_t len;
string stuff;

stream.read ((char *)&len, sizeof(size_t));
stream.read ((char *)&stuff, len);

I'm writing it this way:

ostringstream temp;
temp << p.bee;
string tempbee = temp.str();


size_t len = sizeof(tempbee);
stream.write ((char *)&len, sizeof(tempbee));
stream.write ((char *)&tempbee, len);

Your code should look like:

size_t len;
string stuff;

stream.read ((char *)&len, sizeof(size_t));
stuff.resize(len,0x00);
stream.read ((char *)&stuff[0], len);

size_t len = tempbee.size();
stream.write ((char *)&len, sizeof(size_t));
stream.write ((char *)&tempbee[0], len);

Also expect problems with len 's endianess , when transferring these files between different machine architectures.

To solve the endianess problem, you can define a compatibility format for your file (eg use always network byte order (aka big endian)) to write the length and use the functions from the ntohl() , htonl() family, to convert to/from the length value.

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