3

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?

4
  • 1
    Whilst what you're doing is perfectly valid (don't forget to open the ofstream in binary mode.. whether your data is binary or not, frankly) I would have used vector<char> for the added feel-good factor. Any reason you didn't? Commented Mar 18, 2011 at 16:51
  • @Tomalak: I am using a set of transformer classes that accept and return string. string seemed a convenient interface for manipulating buffers, like appending/substituting into another content etc. I though at one point to define a binaryString as basic_string<unsigned char>, but it required too much time for refactoring which I didn't have at that time. But could I use the << operator with vector<char>? Commented Mar 18, 2011 at 17:14
  • Nope. But then again I'd not want to use << for binary data anyway, as my brain reads it as "formatted output" which is not what you're doing. Again, it's perfectly valid, but I just would not confuse my brain like that. :) The native appending is certainly useful, though. Commented Mar 19, 2011 at 3:26
  • @TomalakGeret'kal et. al...may I draw your attention to this related question: stackoverflow.com/questions/8230786/… Commented Nov 23, 2011 at 11:39

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.