Skip to main content

Stream and file stream classes

Short answer

A stream is a sequence of bytes flowing between program and I/O device. For file I/O, ifstream reads, ofstream writes, fstream does both, and filebuf manages the buffer; all derived from ios offer open(), close() and eof().

What do you mean by stream? Explain different stream class for file input/output.

Stream

A stream is a sequence of bytes that flows between a program and an I/O device (keyboard, monitor, file). Input streams carry data into the program and output streams carry data out. C++ treats all devices uniformly as streams, so the same operators >> and << work with the console and with files.

Stream classes for file I/O

Declared in <fstream>:

ClassBase classPurpose
ifstreamistreamReads from a file (input); members open(), get(), getline(), read(), seekg(), tellg()
ofstreamostreamWrites to a file (output); members open(), put(), write(), seekp(), tellp()
fstreamiostreamReads and writes the same file
filebufstreambufManages the file buffer and the actual transfer of data

ifstream, ofstream and fstream are derived from ios (through istream/ostream), so they share the formatting and error-state functions. Functions common to all three are open(), close(), is_open() and eof(). filebuf is not derived from ios; it is the buffer that each file stream uses internally.

ofstream out("a.txt");   // output file
out << "Hello";
out.close();
ifstream in("a.txt");    // input file

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →