3.4 Molecule Input and Output with Files

In addition to standard in and standard out, OEChem's oemolstreams also support reading from files. To open a file, use the open method with the required filename. For input oemolstreams, if the file doesn't exist the open fails and returns false, for output oemolstreams, the output file is created if it didn't previously exist and overwritten if it did. If a null pointer, (char*)0, is passed as the filename argument to open, an oemolistream will use cin, and an oemolostream will use cout. Much like regular file I/O, oemolstreams can be closed after use, using the close member function. oemolstreams are automatically closed by their destructors.

#include "oechem.h"
#include <iostream>

using namespace OEChem;
using namespace OESystem;
using namespace std;

int main()
{
  OEMol mol;
  oemolistream ims;
  oemolostream oms;

  if (ims.open("input.sdf"))
  {
    if (oms.open("output.mol2"))
    {
      while (ims >> mol)
        oms << mol;
    }
    else cerr << "Error: Unable to create output.mol2" << endl;
  }
  else cerr << "Error: Unable to read input.sdf" << endl;
  return 0;
}

One convenient feature of the open method of oemolstreams is that they set the file format associated with stream from the file extension of the filename used as an argument. The example above converts the file input.sdf in MDL file format into the file output.mol2 in Sybyl mol2 file format. This behavior can be overridden by calling SetFormat after the open but before the first connection table is read or written to a stream.