here is code
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ofstream out("test", ios::out | ios::binary);
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}
double num = 100.45;
char str[] = "www.java2s.com";
out.write((char *) &num, sizeof(double));
out.write(str, strlen(str));
out.close();
return 0;
}
i dont understand only this
out.write((char *) &num, sizeof(double));
why we need (char *)&num?or sizeof(double)?
writetakes two parameters, achar*and a length.&numis actually adouble*. It’s the value we want, but it’s the wrong type, and the compiler would complain. The(char*)tells the compiler to treat this as achar*. Basically, it says to the compiler “Shutup. I know what I’m doing”.sizeof(double)is the size of the double in characters. (Usually, this is 8).Together, they say to write the 8 bytes starting at the address given by &num. (or in other words, write out the bytes that make up num)