writing binary data (std::string) to an std::ofstream?

谁都会走 提交于 2019-12-02 04:36:48

问题


I have an std::string object containing binary data which I need to write to a file. Can ofstream f("name"); f << s; be problematic in any way? I need to read the data back exactly as it was originally.

I can of course use fwrite(s.c_str(), s.size(), 1, filep), are there any pros / cons to either method?


回答1:


You should be ok as long as you open the ofstream for binary access.

ofstream f("name", ios::binary | ios::out); 
f << s;

Don't forget to open your file in binary mode when reading the data back in as well.



来源:https://stackoverflow.com/questions/5355163/writing-binary-data-stdstring-to-an-stdofstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!