Object Oriented Programming · Unit 8 · 6 hrs
File handling
Exam-focused notes for File handling (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.
File handling in short
This unit covers C++'s stream based I/O system in full: the class hierarchy behind cin and cout, unformatted and formatted console I/O, overloading the stream operators for a user defined type, and then file handling, opening and closing files, reading and writing them, moving a file's internal pointers, sequential versus random access, and checking for errors during file operations.
What this unit covers
- Stream Class Hierarchy for Console Input/Output
- Unformatted Input/Output
- Formatted Input/Output with ios Member functions
- Formatting with Manipulators
- Stream Operator Overloading
- File Input/output with Streams
- Opening and Closing files
- Read/Write from File
- File Access Pointers and their Manipulators
- Sequential and Random Access to File
- Testing Errors during File Operations
Stream Class Hierarchy for Console Input/Output
2080 · 5 marks
What do you mean by stream? Explain different stream class for file input/output. [5]
Show solved answerHide answer
Stream and Stream Classes for File I/O in C++
What is a Stream?
A stream is a sequence of bytes flowing between a program and an input/output device (such as a file, keyboard, or screen). It acts as an abstraction layer between the program and the actual device.
- We have been using the
iostreamstandard library, which providescinandcoutfor reading from standard input and writing to standard output respectively. - For file-based I/O, C++ provides another standard library called
fstream, which defines specialized stream classes to read from and write to files.
To perform file processing in C++, the header file
<fstream>must be included in the source file.
Stream Classes for File Input/Output
The fstream library defines three main data types (stream classes):
1. ifstream (Input File Stream)
- Represents the input file stream.
- Used to read information from files.
- Derived from
istream.
Example:
#include <fstream>
using namespace std;
int main() {
ifstream fin;
fin.open("data.txt"); // open file for reading
char ch;
while (fin >> ch)
cout << ch;
fin.close();
return 0;
}
2. ofstream (Output File Stream)
- Represents the output file stream.
- Used to create files and write information to files.
- Derived from
ostream.
Example:
#include <fstream>
using namespace std;
int main() {
ofstream fout;
fout.open("data.txt"); // open file for writing
fout << "Hello, File!";
fout.close();
return 0;
}
3. fstream (File Stream)
- Represents the general file stream.
- Has the capabilities of both
ifstreamandofstream. - Can create files, write information to files, and read information from files.
Example:
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("data.txt", ios::in | ios::out); // read and write
file << "Writing data";
file.close();
return 0;
}
Summary Table
| Class | Purpose | Operation |
|---|---|---|
ifstream | Input file stream | Read from files |
ofstream | Output file stream | Create and write to files |
fstream | General file stream | Read and write to files |
File Pointer Manipulation Functions
The stream classes also support functions to manage file pointer positions:
| Function | Description |
|---|---|
seekg() | Moves the get (input) pointer to a specified location |
seekp() | Moves the put (output) pointer to a specified location |
tellg() | Returns the current position of the get pointer |
tellp() | Returns the current position of the put pointer |
These functions allow random access within a file, enabling reading or writing at any desired position.
2075 · 10 marks
Briefly explain the hierarchy of stream classes. Write a program that overloads extraction and insertion operators.[10]
Show solved answerHide answer
Hierarchy of Stream Classes and Operator Overloading
Part 1: Hierarchy of Stream Classes
C++ provides a rich set of stream classes for performing input/output operations. These classes are organized in a hierarchy, all defined in the header files <iostream>, <fstream>, and <sstream>.
Stream Class Hierarchy Diagram
ios (base class)
|
istream ostream
(input) (output)
\ /
\ /
iostream
(input+output)
/ | \
/ | \
ifstream fstream ofstream
(file in) (file in/out) (file out)
Description of Each Class
| Class | Header | Description |
|---|---|---|
ios | <ios> | Base class for all stream classes. Provides common properties like format flags, error state bits, etc. |
istream | <iostream> | Derived from ios. Handles input operations. Contains cin object and defines >> (extraction operator). |
ostream | <iostream> | Derived from ios. Handles output operations. Contains cout, cerr, clog objects and defines << (insertion operator). |
iostream | <iostream> | Derived from both istream and ostream. Supports both input and output. |
ifstream | <fstream> | Derived from istream. Used for reading from files. |
ofstream | <fstream> | Derived from ostream. Used for writing to files. |
fstream | <fstream> | Derived from iostream. Used for both reading and writing files. |
Key Points
coutis an object ofostreamclasscinis an object ofistreamclass- Writing to a file uses an
ofstreamorfstreamobject instead ofcout, but uses the same<<operator - Reading from a file uses an
ifstreamorfstreamobject instead ofcin, but uses the same>>operator
Part 2: Overloading Extraction (>>) and Insertion (<<) Operators
Important Rules (from notes)
coutis an object ofostreamclass andcinis an object ofistreamclass.- These operators must be overloaded as global functions (not member functions).
- To allow access to private data members, they must be declared as friend functions inside the class.
Syntax
friend ostream& operator<<(ostream& out, const ClassName& obj);
friend istream& operator>>(istream& in, ClassName& obj);
Complete Program
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor
Complex() {
real = 0;
imag = 0;
}
Complex(float r, float i) {
real = r;
imag = i;
}
// Friend function to overload insertion operator (<<)
// Used for output: cout << object
friend ostream& operator<<(ostream& out, const Complex& c) {
out << "Real Part : " << c.real << endl;
out << "Imaginary Part: " << c.imag << endl;
return out;
}
// Friend function to overload extraction operator (>>)
// Used for input: cin >> object
friend istream& operator>>(istream& in, Complex& c) {
cout << "Enter real part: ";
in >> c.real;
cout << "Enter imaginary part: ";
in >> c.imag;
return in;
}
};
int main() {
Complex c1, c2;
// Using overloaded >> operator
cout << "--- Input for Complex Number 1 ---" << endl;
cin >> c1;
cout << "--- Input for Complex Number 2 ---" << endl;
cin >> c2;
// Using overloaded << operator
cout << "\n--- Complex Number 1 ---" << endl;
cout << c1;
cout << "--- Complex Number 2 ---" << endl;
cout << c2;
return 0;
}
Sample Output
--- Input for Complex Number 1 ---
Enter real part: 3
Enter imaginary part: 4
--- Input for Complex Number 2 ---
Enter real part: 1
Enter imaginary part: 2
--- Complex Number 1 ---
Real Part : 3
Imaginary Part: 4
--- Complex Number 2 ---
Real Part : 1
Imaginary Part: 2
Explanation of Key Points
| Point | Explanation |
|---|---|
friend keyword | Allows the global function to access private members real and imag |
ostream& out | Reference to the output stream object (cout) |
istream& in | Reference to the input stream object (cin) |
return out / return in | Returning the stream reference allows chaining like cout << c1 << c2 |
| Global function | These are NOT member functions; they are defined outside the class |
Note: The operators must return a reference to the stream (
ostream&oristream&) so that chained operations likecout << c1 << c2work correctly.
File Access Pointers and their Manipulators
2079 · 5 marks
Write a program to illustrate the use of seekg() and tellg(). [5]
Unformatted Input/Output
2078 · 5 marks
What is the use of get and getline functions? Explain with suitable example. [5]
2075 · 5 marks
How is character I/O different from Binary I/O? Explain with examples. [5]
File Input/output with Streams
2078 · 5 marks
What is meant by stream? Write a program that reads content of file data.txt and displays the content in monitor. [5]
2080.1 · 5 marks
Write a program that stores information of employees in a file and displays the file's content in ascending order of their salary. [5]
Read/Write from File
2076 · 5 marks
Which function can be used for reading and writing object? Define briefly. Write a program that reads values of two objects of students class (assume data members are id, name, and level) and display the data in monitor. [5]
Make Unit 8 stick
Practice CSC166 with flashcards & quizzes