Write a C++ struct to a file and read file using another programming language?
<p>I have a challenging situation; we will have programs on Mac, PC, iOS and Android receiving files in a legacy format and parsing data from those files. We cannot change how those files are created.</p>

<p>The files are produced by a C++ program filling a struct with numbers and Strings and then writing it out. Here's a sanitized version.</p>

<pre><code>struct MyObject {
String Kfkj(MAXKYS); 
String Oern(MAXKYS);
String Vdflj(MAXKYS, 9); 
int Muic;
int Tdfkj;
int VdfkAsdk;
int SsdjsdDsldsk; 
int Ndsoief; 
String TdflsajPdlj; 
String TdckjdfPas; 
String AdsfakjIdd;
int IdkfjdKasdkj;
int AsadkjaKadkja(MAXKYS); 
int Kasldsdkj;
bool Usadl;
String PsadkjOasdj(9); 
String PasdkjOsdkj;
};
</code></pre>

<p>Primitives and Strings, as you can see.</p>

<p>Then here is how they write it out to a file:</p>

<pre><code>MyInstance MyObject;
FileName = "C:\MyFile.ab2"
ofstream fout (FileName, ios::binary);
fout.write((char*)&amp; MyInstance, sizeof(MyInstance));
</code></pre>

<p>There is no option for us to translate it once and then distribute the file to other platforms; we must translate it on each and every different platform, and this is what we have to work with.  I'd appreciate any information on how C++ serializes data, so we know how to parse the file.</p>

<p>EDIT: solution</p>

<p>The feedback I received from multiple answers here was VERY helpful. Using that, I did extensive analysis with hex editors and discovered:</p>

<ul>
<li>the elements come in the file one after another</li>
<li>a "String," in this case, starts with an int describing how many characters follow the int for that String. If the String does not exist, it will still have that int with a value of 0.</li>
<li>integers, for the files and machines I saw, are two bytes, little-endian, and MOSTLY unsigned (there were a few that were signed, just to keep me on my toes)</li>
<li>the boolean was two bytes, with apparently -1 (FF FF) representing "true"</li>
</ul>

<p>So far we have not ran into issues with different padding or endianness on different devices, but those are very real concerns. The skilled notes and warnings in these answers provides us with more ammunition to try to convince the client to change to a less fragile alternative, such as XML or JSON, for transferring data online across platforms.</p>

<p>As for those of you asking if the developer was fired... well, let's just say their code is very old, but after multiple conversations we're still having trouble convincing them writing out the C++ struct and trying to read that on different platforms is not a good idea.</p>
