I’m working on an assignment and I’m getting stuck on one part of it, the output of integers and doubles to a binary file.
I know I need to use the write() function along with using the binary flag for the output stream, however write() requires a character array to output. When I’m outputting a regular string I can just typecast it using (char *) or use the .c_str() function, however I’m having trouble with the doubles and integers.
How would I go about outputting integers and doubles to binary?
You can dereference your variable, and then cast the pointer to a
char*, then usesizeof()to determine how many bytes to write. For instance:Also, if you need the file to be portable, you might want to for instance convert the variable to network byte order first, using the various hton functions (when saving), and ntoh functions (when reading back) – although that only goes for integers.