Whats the difference between ofstream “<<” a

2020-04-03 16:07发布

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.

2条回答
Lonely孤独者°
2楼-- · 2020-04-03 16:45

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.

查看更多
我命由我不由天
3楼-- · 2020-04-03 16:47

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)

查看更多
登录 后发表回答