Reputation: 2096
I had opened a file in binary mode and like to write to an file .
std::ofstream ofile("file.txt",ios_base::binary)
int a = 1;
float f = 0.1;
std::string str = 10;
ofile << a << f<< str;
I would like to know what is the difference between using <<
and ofile.write
.
Which is the best and effective to write in binary mode?
Upvotes: 12
Views: 8247
Reputation: 1133
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)
Upvotes: 2
Reputation: 103713
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.
Upvotes: 14