Tuesday, September 1, 2009

Streams

Most programs have some kind of I/O operations:
  • Reading data from a file on the computer's disk into the program
  • Saving the results of the program into a file on the disk for future use
There must be a way in a programming language to represent the real world disk files in such a way that a program can understand them. Usually a special data type that offers operations for reading and writing data is used. In C++ a data type called a stream is used for this purpose. In fact, besides file I/O, all input and output operations in C++ are done with streams.

The stream can be thought of as a line of characters following in a specific order in one direction without ever changing their order.
  • Only the first character of the stream can be read from the stream ( with the operation get() )
  • Writing can only be done after the last character in the stream( with the operation put() )
All other stream operations can be implemented with get and put. Not changing the order of characters in a stream is essential:
  • If the user types "abcdef" on a keyboard undoubtedly the program gets the same characters in the same order from the input stream(cin)
  • If the program writes characters into a stream connected to a file it is desirable that the characters are saved in the same order they were written into the stream
Streams are sequential in nature: data can only be managed in the same order it is in the stream. A stream is simply a sequence of bytes, that means, if a program is interested in the fifth character in the user's input, the preceding four characters must be read first. The same applies to a stream connected to a file: the file must be read from beginning to end. In reality, disk files can be read and written in an arbitrary order.

A stream is usually connected to a file, the screen or the keyboard. However, streams can also be used to connect two programs to each other. The interesting thing is that streams can always be handled in the same way, regardless of what they happen to be connected to.

Reference: cplusplus, msdn, exforsys


Previous post

Next post


No comments:

Post a Comment