(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Input and Output Streams

Description: General usage notes for input-output streams.

Keywords: ecl streams

Tutorial Level: INTERMEDIATE


Ecl streams work on top of ecl io devices.


Each stream-device pair can be instantiated via the generic TextStream object and the underlying device opened via the device() member method. For example,

   1 TextStream<OFile> stream;
   2 stream.device().open("dude.txt",New);

The console device is a special case - it is automatically opened.

Convenience Classes

The preferred method of instantiation is via the constructor in the convenience classes. The convenience classes are specialised interfaces that inherit from the appropriate Textstream type (dependant on the template parameter). Examples, SerialStream, OFileStream. Rather than calling stream.device().open(...) directly, you can use their constructors to instantiate the stream. They are also more convenient than typing out template parameters continuously.

   1 OFileStream stream("dude.txt",New);

Output Streams

Output streams function similarly to the familiar cout stream. The primary advantage being that they can easily be attached to any standard ecl io device. They can also be used with the ecl formatter classes.

   1 OFileStream ostream;
   2 Format<double> format; format.width(5); format.precision(2);
   3 double d = 1.0/3.0;
   4 ostream << format(d);  // This will send 0.33 to the stream.
   5 ostream.flush();

Input Streams

There are three ways to utilise an input stream:

  • reading element by element (separated by whitespace or newlines).
  • reading raw characters (you must call enableRawCharReads()).
  • reading line by line (not yet enabled).

The first method is similar to the familiar cin, it will take a string and convert it to the requested type.

   1 IConsoleStream istream;
   2 double d;
   3 istream >> d;

The second method is sometimes useful when communicated with raw character devices (e.g. a serial line). In this situation, you must simply make use of the char input operator.

   1 SerialStream serial_stream;
   2 char c;
   3 if ( serial_stream.device().remaining() ) {
   4      serial_stream >> c;
   5 }

The third method has not yet been implemented.

Error Checking

  • Output streams can generate errors that are not so easily checked compared with handling devices directly. To check for failure, ecl streams use a mechanism similar to that of the standard cout stream.

   1 ostream << 32.1;
   2 if ( ostream.fail() ) {
   3     std::cout << ostream.errorStatus().what() << std::endl;
   4 }

Wiki: ecl_streams/Tutorials/Input and Output Streams (last edited 2012-01-29 23:41:39 by DanielStonier)