Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

Like to know what the difference between writing using "<<" and using "ofile.write" . which is the best and effective to write in binary mode.

like image 883
Verve Innovation Avatar asked Dec 01 '10 22:12

Verve Innovation


People also ask

What is the meaning of ofstream?

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.

What is the difference between ofstream and fstream?

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.

What is difference between istream and ifstream?

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.


2 Answers

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.

like image 185
Benjamin Lindley Avatar answered Sep 22 '22 04:09

Benjamin Lindley


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)

like image 31
cjh Avatar answered Sep 21 '22 04:09

cjh