I/O States


Most Recursion Software I/O objects maintain state information that can be used to determine if the stream or device is ready for a read or write. All I/O objects respond to the following messages.

One commonly used I/O object state is end-of-input. This state can be used even in no-error situations. The following example illustrates a simple use of the end-of-input state.

Example <ospace/io/examples/state1.cpp>
#include <iostream>
#include <ospace/file.h>

void
write()
  {
  os_file file
    (
    "state1.txt",
    os_open_control::create_always,
    os_io_control::write_only_access
    );
  file.write( "123", 3 );
  }

void
read()
  {
  os_file file( "state1.txt" ); // Open existing file.

  while ( file.good() )
    {
    char result = '.';
    file.read( &result, 1 );
    cout << "eof() = " << file.eof();
    cout << "    good() = " << file.good();
    cout << "    result =  " << result << endl;
    }
  }

void
main()
  {
  os_file_toolkit initialize;

  write();
  read();
  }

eof() = 0    good() = 1    result =  1
eof() = 0    good() = 1    result =  2
eof() = 0    good() = 1    result =  3
eof() = 1    good() = 0    result =  .

You can program most I/O objects to generate an exception on end-of-input. Refer to the "Exception Handling" section of Introduction to Communications for more information on errors.

To enable exception generation when end-of-input occurs, use the event_on_eof() message. The following example illustrates error generation when os_file encounters end-of-input.

Example <ospace/io/examples/state2.cpp>
#include <iostream>
#include <ospace/file.h>

void
main()
  {
  os_file_toolkit initialize;

  os_file file( "state2.cpp" ); // Open this file for read-only.
  file.event_on_eof ( true ); // Generate event on end-of-file.

  int bytes = 0;
  char line[ 256 ]; // Line buffer.

  try
    {
    while ( file.good() )
    bytes += file.read( line, sizeof( line ) );
    }
  catch ( os_file_toolkit_error& error )
    {
    cout << "Caught os_file_toolkit_error: " << endl;
    cout << 't' << error << endl;
    cout << "Read " << bytes << " bytes" << endl;
    }
  }

Caught os_file_toolkit_error:
        eof_encountered:  [file.cpp:204]
Read 890 bytes

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