file


The os_file class provides a portable interface for accessing and manipulating text and binary files. In addition to standard I/O facilities, os_file provides an interface for random access positioning, record locking, and truncation. This class also has a "close on destruction" option to prevent data loss.

The following example demonstrates random access and truncation.

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

void
main()
  {
  os_file_toolkit initialize;

  // Create a new file.
  os_file file
    (
    "file1.txt",
    os_open_control::create_always,
    os_io_control::read_write_access
    );
  cout << "Position = " << file.tell() << endl;
  char ch;

  // Write the alphabet forwards, one character at a time.
  for ( int i = 0; i < 26; i++ )
    {
    ch = 'a' + i;
    file.write( &ch, 1 );
    }
  cout << "Position = " << file.tell() << endl;
  file.rewind();

  // Read the alphabet forwards, one character at a time.
  for ( int j = 0; j < 26; j++ )
    {
    file.read( &ch, 1 );
    cout << ch;
    }
  cout << endl;

  // Read the alphabet backwards, one character at a time.
  for ( int k = 25; k >= 0; k-- )
    {
    file.seek( k ); // Set the file pointer to the kth character.
    file.read( &ch, 1 );
    cout << ch;
    }
  cout << endl;
  file.resize_to( 10 ); // Truncate the file to be 10 chars long.
  file.rewind(); // Set the file pointer to the beginning of the file.

  // Read a truncated alphabet forwards, one character at a time.
  while ( true )
    {
    file.read( &ch, 1 );
    if ( file.eof() ) // Stop if the end of the file has been reached.
      break;
    cout << ch;
    }
  cout << endl;
  file.close();

  os_file_system::remove( "file1.txt" ); // Remove the file.
  }

Position = 0
Position = 26
abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba
abcdefghij

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