What I do not understand is how the write() function can output a four byte integer value ('n') after casting it to a one byte char pointer.
The declaration for the write() function is as follows: ostream& write (const char* s , streamsize len);
To access the next value, presumably 's' would be incremented by one byte as any other char pointer. However, since each value of the 'n' array is four bytes long it would seem that 's' would now point to the second byte of the first item in the 'n' array. Yet, this program appears to function as if, after being incremented, 's' points to the second value in the 'n' array.
What am I missing?
Thanks for any clarification,
Ben
There is no "incrementing"-----the write() function does not care that it is being handed an array. It is given a pointer and told to write out the next 20 bytes (because sizeof(n) is sizeof(int)*5, you can check this).
you can also use fstream to write to files , both text and binary , reading and writing happens the same way.
Code:
fstream mystream("myfile" ,std::ios::binary|std:ios:in); // as in reading a files
mystream.read((char *) myarray ,sizeof(myarray));
// if you are reading header of any file then you need to know the structure used to write //that header
// so instead of array define the structure and then read into that structure
// same for the writing. std::ios::out)
// don't forget to flush and close the steam when you are done with it.
Aha! I was misinterpreting the sizeof command. It all fits together now.
Thank you very much!
Be VERY VERY VERY (VERY) careful when calling sizeof on arrays. Arrays have a tendency to decay into simple pointers, at which point the sizeof will not be what you think it is...
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks