title: c++ Reading string from binary file using fstream
body: <p>I am trying to read a string from a binary file but cant seem to get it to work. I am a pretty new to c++. Can anybody help please? Thanks.</p>
  
  <pre><code>string Name = "Shaun";
  unsigned short int StringLength = 0;
  
  int main()
  {
      StringLength = Name.size();
  
      ofstream oFile("File.txt", ios::binary|ios::out);
      oFile.write((char*)&amp;StringLength, sizeof(unsigned short int));
      oFile.write(Name.c_str(), StringLength);
      oFile.close();
  
      StringLength = 0;
      Name = "NoName";
  
      ifstream iFile("File.txt", ios::binary|ios::in);
      if(!iFile.is_open())
          cout &lt;&lt; "Failed" &lt;&lt; endl;
      else
      {
          iFile.read((char *)&amp;StringLength, sizeof(unsigned short int));
          iFile.read((char *)&amp;Name, StringLength);
      }
  
      cout &lt;&lt; StringLength &lt;&lt; " " &lt;&lt; Name &lt;&lt; endl;
  
      system("Pause&gt;NUL");
      return 0;
  }
  </code></pre>