Using Streaming<ToolKit> with a File


The os_file class has an associated device adapter for use with Streaming<ToolKit>. With an automatic conversion operator, you can supply an os_file whenever an os_adapter is expected. Refer to Streaming<ToolKit> Universal Streaming Service and Streaming<ToolKit> Text Streams for more information on streams.

The following example shows how to create a text stream on a file. write() uses an output stream to send text to a file, and read() uses an input stream to read text from a file.

Example <ospace/file/examples/tstream1.cpp>
#include <iostream>
#include <ospace/file.h>
#include <ospace/stream.h>

void
write( os_adapter device )
  {
  os_otstream stream( device );
  char* txt = "This is a line of text.";
  int num = 42;
  cout << "Writing: " << txt << endl << num << endl;
  stream << txt << endl << num << endl;
  }

void
read( os_adapter device )
  {
  os_itstream stream( device );
  char buffer[ 32 ];
  int num = -1;
  stream.getline( buffer, sizeof( buffer ) );
  stream >> num;
  cout << "Read: " << buffer << endl << num << endl;
  }

void
main()
  {
  os_file_toolkit init_file;
  os_streaming_toolkit init_streaming;

  // Create a file.
  os_file file
    (
    "tstream1.txt",
    os_open_control::create_always,
    os_io_control::read_write_access
    );

  write( file );
  file.rewind();
  read( file );
  }

Writing: This is a line of text.
42
Read: This is a line of text.
42

The next example shows how to create an os_bstream on a file. write() uses the stream to save objects to a file, and read() uses the stream to restore objects from a file.

Example <ospace/file/examples/bstream1.cpp>
#include <iostream>
#include <ospace/file.h>
#include <ospace/stream.h>
#include <ospace/time.h>
#include <ospace/uss/time.h>

void
write( os_adapter device )
  {
  os_bstream stream( device );
  os_date today = os_date::today();
  os_time now = os_time::now();
  cout << "Writing: " << today << " at " << now << endl;
  stream << today << now;
  }

void
read( os_adapter device )
  {
  os_bstream stream( device );
  os_date d;
  os_time t;
  stream >> d >> t;
  cout << "Read: " << d << " at " << t << endl;
  }

void
main()
  {
  os_file_toolkit init_file;
  os_streaming_toolkit init_streaming;
  os_time_toolkit init_time;

  // Create a new file.
  os_file file
    (
    "bstream1.bin",
    os_open_control::create_always,
    os_io_control::read_write_access
    );

  write( file );
  file.rewind();
  read( file );
  }

Writing: 10/1/96 at 16:02:09
Read: 10/1/96 at 16:02:09

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