title: C++ file formatting and output to a file
body: <p>Suppose I have a piece of code that prints something,like this,</p>
  
  <pre><code>u_int packetCount = 0;
      while (int returnValue = pcap_next_ex(pcap, &amp;header, &amp;data) &gt;= 0)
      {
  
          // Show the packet number
          printf("Packet # %i\n", ++packetCount);
  
          // Show the size in bytes of the packet
          printf("Packet size: %d bytes\n", header-&gt;len);
  
          // Show a warning if the length captured is different
          if (header-&gt;len != header-&gt;caplen)
              printf("Warning! Capture size different than packet size: %ld bytes\n", header-&gt;len);
  
          // Show Epoch Time
          printf("Epoch Time: %d:%d seconds\n", header-&gt;ts.tv_sec, header-&gt;ts.tv_usec);
  
          // loop through the packet and print it as hexidecimal representations of octets
          // We also have a function that does this similarly below: PrintData()
          for (u_int i=0; (i &lt; header-&gt;caplen ) ; i++)
          {
              // Start printing on the next after every 16 octets
              if ( (i % 16) == 0) printf("\n");
  
              // Print each octet as hex (x), make sure there is always two characters (.2).
              printf("%.2x ", data[i]);
  
          }
  
          // Add two lines between packets
          printf("\n\n");
      }
  </code></pre>
  
  <p>The last line gives me output like </p>
  
  <pre class="lang-none prettyprint-override"><code>Packet # 39
  Packet size: 54 bytes
  Epoch Time: 1084443432:328438 seconds
  
  fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00 
  00 28 0f 5c 40 00 80 06 91 d8 91 fe a0 ed 41 d0 
  e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 48 50 10 
  24 14 31 71 00 00 
  
  Packet # 40
  Packet size: 54 bytes
  Epoch Time: 1084443445:216971 seconds
  
  00 00 01 00 00 00 fe ff 20 00 01 00 08 00 45 00 
  00 28 c0 ad 40 00 2f 06 31 87 41 d0 e4 df 91 fe 
  a0 ed 00 50 0d 2c 11 4c a9 48 38 af ff f3 50 11 
  19 20 3c 64 00 00 
  
  Packet # 41
  Packet size: 54 bytes
  Epoch Time: 1084443445:216971 seconds
  
  fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00 
  00 28 0f 5f 40 00 80 06 91 d5 91 fe a0 ed 41 d0 
  e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 49 50 10 
  24 14 31 70 00 00 
  
  Packet # 42
  Packet size: 54 bytes
  Epoch Time: 1084443457:374452 seconds
  
  fe ff 20 00 01 00 00 00 01 00 00 00 08 00 45 00 
  00 28 0f 62 40 00 80 06 91 d2 91 fe a0 ed 41 d0 
  e4 df 0d 2c 00 50 38 af ff f3 11 4c a9 49 50 11 
  24 14 31 6f 00 00 
  </code></pre>
  
  <p>I need to print the output of this line "<code>printf("%.2x ", data[i]);</code>
  " and then write this output into a file in C++. Can I please know how to do it?</p>