title: Can I read in binary data with istream in c++?
body: <p>Right now I am using istream to read in data.  I have both text which I would like to read in as strings and numbers, and hashes which are read into character arrays.  Since hashes are effectively random, I am hitting snags when I try to read it back in and hit EOF (which is part of the hash).  Is there a way to accomplish this without resorting to fread.  Also, is there a to use both istream and fread some I don't have to parse the integers and strings by hand.  Finally, what is the best way to use fgets to get a string of unknown length.</p>
  
  <p>Thanks,
  Eric</p>
  
  <p>EDIT:
  Here is the code:</p>
  
  <pre><code>string dummy;
  ifstream in(fileName);
  for(int i=0; i&lt;numVals; i++)
  {
      int hashLen;
      in&gt;&gt;hashLen;
      char cc;
      in.get(cc);//Get the space in between
      cout&lt;&lt;"Got first byte: "&lt;&lt;(int)cc&lt;&lt;endl;
  
      char * hashChars = new char[hashLen];
      in.read(hashChars, hashLen);
      for(int j =0; j &lt;hashLen; j++)
      {
          char c = hashChars[j];
         unsigned char cc = reinterpret_cast&lt;unsigned char&amp;&gt;(c);
          cout&lt;&lt;"Got byte: "&lt;&lt;(int)c&lt;&lt;(int)cc&lt;&lt;endl;
          if(in.fail())
          {
              cout&lt;&lt;"Failed! "&lt;&lt;in.eof()&lt;&lt;" "&lt;&lt;in.bad()&lt;&lt;endl;
          }
      }
  
  delete hashChars;
  
      getline(in,dummy);//get a dummy line
      cout&lt;&lt;"Dummy: "&lt;&lt;dummy&lt;&lt;" numvals: "&lt;&lt;numVals&lt;&lt;" i: "&lt;&lt;i&lt;&lt;" hashLength: "&lt;&lt;hashLen&lt;&lt;endl;
  }
  </code></pre>
  
  <p>My output looks like:</p>
  
  <p>1>Got first byte: 32</p>
  
  <p>1>Got byte: 4 4</p>
  
  <p>1>Got byte: -14 242</p>
  
  <p>1>Got byte: 108 108</p>
  
  <p>1>Got byte: 87 87</p>
  
  <p>1>Got byte: 113 113</p>
  
  <p>1>Got byte: -116 140</p>
  
  <p>1>Got byte: -106 150</p>
  
  <p>1>Got byte: -35 221</p>
  
  <p>1>Got byte: 0 0</p>
  
  <p>1>Got byte: -91 165</p>
  
  <p>1>Got byte: 39 39</p>
  
  <p>1>Got byte: 111 111</p>
  
  <p>1>Got byte: 7 7</p>
  
  <p>1>Got byte: 126 126</p>
  
  <p>1>Got byte: 16 16</p>
  
  <p>1>Got byte: -42 214</p>
  
  <p>1>Dummy:  numvals: 35 i: 12 hashLength: 16</p>
  
  <p>1>Got first byte: 32</p>
  
  <p>1>Got byte: 14 14</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -65 191</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -107 149</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -44 212</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -60 196</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -51 205</p>
  
  <p>1>Failed! 1 0</p>
  
  <p>1>Got byte: -51 205</p>
  
  <p>1>Failed! 1 0</p>