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:
And it worked.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();
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:
And yes, it works fine.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();
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



LinkBack URL
About LinkBacks



I used to be an adventurer like you... then I took an arrow to the knee.