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?

davka
  • 13,974
  • 11
  • 61
  • 86
  • 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` for the added feel-good factor. Any reason you didn't? – Lightness Races in Orbit Mar 18 '11 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`, but it required too much time for refactoring which I didn't have at that time. But could I use the `<<` operator with `vector`? – davka Mar 18 '11 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. – Lightness Races in Orbit Mar 19 '11 at 03:26
  • @TomalakGeret'kal et. al...may I draw your attention to this related question: http://stackoverflow.com/questions/8230786/inserters-and-extractors-reading-writing-binary-data-vs-text/ – HostileFork says dont trust SE Nov 23 '11 at 11:39

1 Answers1

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.

Jon
  • 3,065
  • 1
  • 19
  • 29