aegis said:
How can one portably write out to a binary file an integer value
if fstream's write wants a pointer to char read-only?
Or say a float, etc. What if pointer to float or
pointer to int has different alignment requirements than
for a pointer to char read-only? How do we get around
this?
My understanding is that you are not writing a pointer to float or char
but you write serialized representation of a float or of a char. Then,
when you read it you have to read it into the properly aligned place
that is aligned correspondently by the compiler. While in the file,
alignment does not matter unless you are going to map it to a memory
area (in which case, the representation can't be made portable). So the
only issue seems to be the data size and the format. Unless you want
compression, you may use Java serialization format (IEEE 754 for single-
and double- precision floats and two's complements format for integers,
8-, 16-, 32- and 64- bit, with MSB first (so called "network" order)).
For example (the below is not exactly by the letter of the Standard, but
will work on many systems),
typedef ... Int32; /* this is system-dependent but you can use int32_t
that is available on many systems (theoretically, it's available in
stdint.h on any C system; in practice, you may have to do some
#ifdef-juggling between stdint.h and inttypes.h depending on the system */
/* the following is a concept only, no error processing, also in
practice you might want to use ntohl, htonl or whatever is available on
your system for efficiency. */
#define INT32_CHARS (32/CHAR_BIT)
void writeInt32(ostream &os, Int32 n) {
unsigned char c[INT32_CHARS];
for (int i = INT32_CHARS; --i > 0
c[(INT32_CHARS - 1) - i] = (unsigned char) (n >>
(CHAR_BIT * i));
c[INT32_CHARS - 1] = (unsigned char) n;
os.write(reinterpret_cast<char *>(&c[0]), 4);
}