Recently I have to deal with C++ I/O interface extensively in my job. However, I had not used it directly for a while, so I decided to review/relearn a bit so that I can use it fluently.
At a first glimpse, I found it a bit confusing and complex, given the number of classes and their intertwined inheritance relationships. Then I picked up my old C++ textbook and went through the underlining design concepts of I/O Stream library. Suddenly, things became clear and intuitive.
Here I am going to outline what I had understood:
- The most fundamental concept is stream. Stream is a flow of characters or bytes, which means they have to flow in from one end, and flow out from the other end. The real question remained is what to connect to each end and how.
- For example,
cinobject is a predefined stream objec in STL I/O interface. The ‘input’ end is connected to
stdin, which is (usually) keyboard, the ‘output’ end could be connected to different kinds of data structures in user program, like a
char arrayor a
stringobject and so on. Another example is
ifstreamobject. The input end connects to an open file, output ends again could connect to various data structures in user program. And the bytes stream flow from the open file through
ifstreamobject and then directed to some data structure predefined in user program.
- There are many ways or combinations to connect two ends of a stream, that is why we have many predefined
streamclasses in C++ STL I/O interface. Each I/O class represents one distinct stream concept, and some classes share certain features or components together. Class hierachy can be seen from here).
- Another important concept is buffer. Buffer makes I/O operations more efficient because it reduces frequencies of disk accessing. Every C++
stream class manages a buffer internally, which makes programmers’ life easier when dealing with I/O. There is a base buffer class for the buffer
used internally by c++ stream classes:
streambuf. It is an abstract class which cannot be instantiated directly. However, it has two concrete derived classes -
stringbuf, which are actually used. Normally, a programmer does not need to create a buffer object to deal with I/O stuff since C++ stream classes already take care of that internally.
To conclude, to use C++ I/O interface, a programmer usually does not need to create a memory buffer himself/herself, just create the most appropriate stream class object and connect the object’s input and output end accordingly.