title: How to read/write std::string values from/to binary files
body: <p>I want to write an Item to a binary file, close it, and open it again to read it. The code is simple and straightforward, it compiled and ran without error using Visual Studio 2008. </p>
  
  <p>However, it got 'segment fault' when running with the GCC compiler. </p>
  
  <p>What am I doing wrong?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  class Item
  {
  private:
      string itemID;
      string itemName;
      string itemState;
  
  public:
      Item( const string&amp; id = "i0000", const string&amp; name = "Zero item", const string&amp; state = "not init" )
          : itemID( id ) , itemName( name ) , itemState( state )
      {
  
      }
  
      string&amp; operator []( int x )
      {
          if ( 0 == x )
              return itemID;
          if ( 1 == x )
              return itemName;
          if ( 2 == x )
              return itemState;
  
          return ( string&amp; )"";
      }
  
      const string&amp; operator []( int x ) const
      {
          if ( 0 == x )
              return itemID;
          if ( 1 == x )
              return itemName;
          if ( 2 == x )
              return itemState;
  
          return ( string&amp; )"";
      }
  
  public:
      friend istream&amp; operator &gt;&gt;( istream&amp; i, Item&amp; rhs )
      {
          cout &lt;&lt; " * ItemID: ";
          getline( i, rhs.itemID );
          cout &lt;&lt; " - Item Name: ";
          getline( i, rhs.itemName );
          cout &lt;&lt; " - Item State: ";
          getline( i, rhs.itemState );
          return i;
      }
  
      friend ostream&amp; operator &lt;&lt;( ostream&amp; o, const Item&amp; rhs )
      {
          return o &lt;&lt; "ID = " &lt;&lt; rhs.itemID
                   &lt;&lt; "\nName = " &lt;&lt; rhs.itemName
                   &lt;&lt; "\nState = " &lt;&lt; rhs.itemState &lt;&lt; endl;
      }
  };
  
  void write_to_file( const string&amp; fn, const Item&amp; item )
  {
      fstream outf( fn.c_str(), ios::binary | ios::out );
      Item temp( item );
      outf.write( reinterpret_cast&lt;char *&gt;( &amp;temp ), sizeof( Item ) );
      outf.close();
  }
  
  void read_from_file( const string&amp; fn, Item&amp; item )
  {
      fstream inf( fn.c_str(), ios::binary | ios::in );
  
      if( !inf )
      {
          cout &lt;&lt; "What's wrong?";
      }
      Item temp;
      inf.read( reinterpret_cast&lt;char *&gt;( &amp;temp ), sizeof( Item ) );
      item = temp;
      inf.close();
  }
  
  int main()
  {
      string fn = "a.out";
      //Item it( "12", "Ipad", "Good" );
      //write_to_file( fn, it );
  
  
      Item temp;
      read_from_file( fn, temp );
      cout &lt;&lt; temp;
  
      return 0;
  }
  </code></pre>