title: How can I portably write text fields into a binary file in C++ without the use of third party libraries?
body: <p>I am currently working on a program that needs to read and write simple binary files. The data that these files contain is large enough to make even compressed text files impractical. In these binary files, however, I need to store some metadata as text. I can easily create one or more <code>std::string</code>s in my IO code that can then be stored, but my simplest idea for storing them is something like this:</p>
  
  <pre><code>std::string toStore; //assume that this string is decently long and has only ascii characters in it
  std::vector&lt;unsigned char&gt; output;
  
  unsigned char *strPointer = reinterpret_cast&lt;unsigned char*&gt;(toStore.data());
  output.insert(strPointer, strPointer+toStore.length());
  output.push_back('\0');
  
  std::ofstream fout;
  fout.write(output.data(), output.size());
  </code></pre>
  
  <p>This method, however, has a major problem: because the character encoding on different C++ implementations is not guaranteed to be the same, the file format will be different when it is read or written with different C++ implementations. </p>
  
  <p>I am interested in my program supporting Linux, Mac OS, and Windows with just a recompile (ie. no code changes). These strings contain only ASCII characters. As such, my other idea is to define my own character encoding and use switch statements (or something similar) to convert between it and whatever the implementation's encoding is. This is practical because ASCII doesn't contain many characters. Such a new encoding, however, is not ideal because it will make my files more difficult to read for other programmers wishing to implement my format (which is plausible in the context of what this program is). I could attempt to do the aforementioned technique with ASCII as the character encoding, but this is needlessly inefficient because <em>most</em> compilers will be using ASCII anyway.</p>
  
  <p>Is there some better way to handle this? For example, is there a standard library function to convert a string to its ASCII or Unicode represnetation?</p>