Whats the difference between ofstream "<<" and Write
I had opened a file in binary mode and like to write to an file .
ofstream ofile("file.txt",ios_base::binary)
int a = 1;
float f = 0.1;
string str = 10;
ofile<<a<<f<<str;
Lik开发者_运维问答e to know what the difference between writing using "<<" and using "ofile.write" . which is the best and effective to write in binary mode.
operator<< will format your data as text. Whereas write will output data in the same format as it's stored in ram. So, if you are writing binary files, you want to use write.
However, if you are writing non-pod types, you need to be careful. You can't just say:
write( &mystring, sizeof(std::string) );
You need to have some way to output the actual data, which is not stored in the class or struct itself.
AFAIK write passes the value 'as is' where as the operator<< performs some formatting.
For more see here it has bullet points listing some of the features.
As mentioned, for binary data is is generally preferable to use write as it just outputs the data without any formatting (which is very important for binary data as additional formatting may invalidate the format)
精彩评论