This is a common question for a noob I guess, but I don't seem to be able to find the answer anywhere.
The question is:
I wish to write a fixed sequence of ints, floats, strings etc. etc. to file and then read them back; what is the most effecient method?
I used to do something like:
Code:
ofstream file("file.fil", ios::out | ios::binary | ios::ate);
int i = 5;
float f = 5.6;
string s = "Dogs like cats";
file.write(&i, sizeof(int));
file.write(&f, sizeof(f));
file.write(&s, sizeof(string));
file.close();
And it worked.
When returning to my code in dev-cpp however, that use of the write function was not supported, indeed it only showed me one use of the write() function:
Code:
write(const char *, unsigned int);
(or something very close).
No problem thought I, I simply use:
Code:
ofstream file("file.fil", ios::out | ios::binary | ios::ate);
int i = 5;
float f = 5.6;
string s = "Dogs like cats";
file.write(reinterpret_cast<const char *>(&i), sizeof(int));
file.write(reinterpret_cast<const char *>(&f), sizeof(f));
file.write(reinterpret_cast<const char *>(&s), sizeof(string));
file.close();
And yes, it works fine.
My question is however:
-------------------------------
Is there a better or more correct way to do this? Is this method ok? (I have neverseen the reinterpret_cast method I have used documented anywhere)
Thanks in anticipation
dt