title: Qt: Write Struct to File
body: <p>I'm struggling with writing a <code>struct</code> to a file via <code>QFile</code> in Qt.</p>
  
  <pre><code>typedef struct {
      uint32_t timestamp;
      uint32_t recordType;
      uint32_t payloadLength;
      char* payload;
  } DataPacket;
  </code></pre>
  
  <p>The <code>DataPacket</code> struct is populated elsewhere:</p>
  
  <pre><code>QString dataString = "$GPGSA,M,3,03,23,22,19,17,01,09,31,12,,,,1.9,0.9,1.6*3D";
  
  DataPacket p;
  memset(&amp;p, 0, sizeof(DataPacket));
  p.timestamp = now();
  p.recordType = 1;
  QByteArray arr = dataString.toLatin1();
  p.payloadLength = arr.count();
  p.payload = arr.data();
  
  // Write the data to a log file
  QFile f;
  f.setFileName(outputFile);
  bool ok = f.open(QIODevice::WriteOnly);
  
  if (ok) {
      f.write((char *)&amp;p, sizeof(DataPacket));
      f.close();
  }
  </code></pre>
  
  <p>When I inspect the <code>outputFile</code> log file, the <code>$GPGSA...</code> string is no where to be seen. If I then additionally write the <code>payload</code> field separately:</p>
  
  <pre><code>if (ok) {
      f.write((char *)&amp;p, sizeof(DataPacket));
      f.write(p.payload, p.payloadLength);
      f.close();
  }
  </code></pre>
  
  <p>The <code>$GPGSA</code> string is subsequently written correctly.</p>
  
  <p>I'm missing something...</p>