Raw I/O


To write and read blocks of memory, use the write() and read() functions. These functions act the same as the lowest level write() and read() system calls, except these functions generate errors consistent with other Recursion Software library components. Both operations return the number of bytes actually transferred.

In the following example, one function writes structures to a file, and the other function reads the structures.

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

struct my_struct
  {
  int a;
  double d;
  };

void
display( char* str, my_struct* s, int bytes )
  {
  cout << str << bytes << " bytes: " << s->a << ", " << s->d << endl;
  }

void
write()
  {
  my_struct s1;
  s1.a = 42;
  s1.d = 3.14;
  my_struct s2;
  s2.a = 1;
  s2.d = 2.13;

  // Create and open a file for write only, tuncating existing contents
  os_file file
    (
    "rawio1.bin",
    os_open_control::create_always,
    os_io_control::write_only_access
    );
  int bytes = file.write( (const char*) &s1, sizeof( s1 ) );
  display( "Write ", &s1, bytes );
  bytes = file.write( (const char*) &s2, sizeof( s2 ) );
  display( "Write ", &s2, bytes );
  }

void
read()
  {
  os_file file( "rawio1.bin" );
  my_struct s1;
  int bytes = file.read( (char*) &s1, sizeof( s1 ) );
  display( "Read ", &s1, bytes );
  my_struct s2;
  bytes = file.read( (char*) &s2, sizeof( s2 ) );
  display( "Read ", &s2, bytes );
  os_file_system::remove( "rawio1.bin" );
  }

void
main()
  {
  os_file_toolkit initialize;

  write();
  read();
  }

Write 16 bytes: 42, 3.14
Write 16 bytes: 1, 2.13
Read 16 bytes: 42, 3.14
Read 16 bytes: 1, 2.13

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