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;
Like to know what the difference between writing using "<<" and using "ofile.write" . which is the best and effective to write in binary mode.
ofstream. This data type represents the output file stream and is used to create files and to write information to files. 2. ifstream. This data type represents the input file stream and is used to read information from files.
ofstream inherits from ostream . fstream inherits from iostream , which inherits from both istream and stream . Generally ofstream only supports output operations (i.e. textfile << "hello"), while fstream supports both output and input operations but depending on the flags given when opening the file.
ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With