Character String I/O


To write a null-terminated character string, such as char* , use operator<< . An encoded copy of the character string, along with size and type information, are written.

To read a character string onto the heap, use operator>> .

The primary benefit of character string I/O is the encoding of the string's size with its text providing the following benefits.

Because the string class is binary enabled, it can be used in place of character strings. Refer to the "Object I/O" section of this chapter for more information about object I/O.

The following example demonstrates character string I/O. Note that a type mismatch error occurs when a character string is read back into an int .

Example <ospace/stream/examples/strio1.cpp>
#include <fstream>
#include <ospace/stream.h>

void
write()
  {
  fstream file( "primio2.bin", ios::binary | ios::out | ios::trunc );
  os_bstream stream( os_adapter_for( file ) );

  // Write three char* strings in binary format
  stream << "Systems" << (char*) 0 << "<ToolKit>";
  cout << "Write: Systems, null, <ToolKit>" << endl;
  }

void
read()
  {
  fstream file( "primio2.bin", ios::binary | ios::in );
  os_bstream stream( os_adapter_for( file ) );

  char* str1 = 0;
  stream >> str1; // Read a string into heap.
  cout << "Read: " << str1 << ", " << (void*) str1 << endl;
  delete [] str1;

  char* str2 = 0;
  stream >> str2;
  cout << "Read: " << str2 << ", " << (void*) str2 << endl;

  int i;
  stream >> i; // Try to read a string into an int.
  cout << "Read: " << i << endl;
  }

void
main()
  {
  os_streaming_toolkit initialize;

  try
    {
    write();
    read();
    }
  catch( os_streaming_toolkit_error& error )
    {
    cout << "Caught exception : " << endl;
    cout << '\t' << e.what() << endl;
    cout << '\t' << e.description( e.code() ) << endl;
    }
  }

Write: Systems, null, <ToolKit>
Read: Systems, 0xb4678
Read: '', 0x0
Caught os_streaming_toolkit_error :
        type_mismatch: Tried to read int but got char*[bstream.cpp:1295]
        Attempted to read wrong type.
	

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.