8 File Handling

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.

File handling: notes

Stream Class Hierarchy for Console Input/Output

C++'s I/O system is built around a hierarchy of stream classes declared in <iostream>. ios is the base class for the whole hierarchy and holds the common formatting and status information; istream handles input and is the type of cin, ostream handles output and is the type of cout, and iostream combines both for streams that do both input and output. File I/O reuses this same hierarchy through <fstream>, which adds three further classes: ifstream (derived from istream) for reading from files, ofstream (derived from ostream) for writing to files, and fstream (derived from iostream) for streams that both read and write.

Unformatted Input/Output

Unformatted I/O reads or writes raw characters with no interpretation of their type. cin.get() reads a single character, including spaces and newlines, which >> would otherwise skip. cout.put(c) writes a single character. cin.getline(buffer, size) reads an entire line, up to size - 1 characters or the next newline, into a character array, which is how to read text that contains spaces. cout.write(buffer, n) writes exactly n characters from a buffer.

#include <iostream>
using namespace std;

int main() {
    char name[20];
    cout << "Enter name: ";
    cin.getline(name, 20);
    cout.write(name, 6);
    cout << endl;
    return 0;
}

Formatted Input/Output with ios Member functions

Formatted I/O controls exactly how output is laid out, using member functions of ios (declared via <iomanip>). width(n) sets the minimum field width of the next value. fill(c) sets the character used to pad unused space in a field. precision(n) sets the number of digits shown for floating point output. setf() and unsetf() set and clear format flags, such as showing values in a particular base or with a fixed number of decimal places.

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 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 iostream standard library, which provides cin and cout for 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 ifstream and ofstream.
  • 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

ClassPurposeOperation
ifstreamInput file streamRead from files
ofstreamOutput file streamCreate and write to files
fstreamGeneral file streamRead and write to files

File Pointer Manipulation Functions

The stream classes also support functions to manage file pointer positions:

FunctionDescription
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.

Open this answer on its own page →

2075 · 10 marks

Briefly explain the hierarchy of stream classes. Write a program that overloads extraction and insertion operators.[10]

Show solved 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

ClassHeaderDescription
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

  • cout is an object of ostream class
  • cin is an object of istream class
  • Writing to a file uses an ofstream or fstream object instead of cout, but uses the same << operator
  • Reading from a file uses an ifstream or fstream object instead of cin, but uses the same >> operator

Part 2: Overloading Extraction (>>) and Insertion (<<) Operators

Important Rules (from notes)

  1. cout is an object of ostream class and cin is an object of istream class.
  2. These operators must be overloaded as global functions (not member functions).
  3. 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

PointExplanation
friend keywordAllows the global function to access private members real and imag
ostream& outReference to the output stream object (cout)
istream& inReference to the input stream object (cin)
return out / return inReturning the stream reference allows chaining like cout << c1 << c2
Global functionThese are NOT member functions; they are defined outside the class

Note: The operators must return a reference to the stream (ostream& or istream&) so that chained operations like cout << c1 << c2 work correctly.

Open this answer on its own page →

File Access Pointers and their Manipulators

2079 · 5 marks

Write a program to illustrate the use of seekg() and tellg(). [5]

  • tellg() -- Returns the current get pointer position (current read position) in the file as a number of bytes from the beginning. - seekg() -- Moves the get pointer to a specified position in the file so that the next read operation starts from that position. These functions are used with input ...
Open this answer on its own page →

Unformatted Input/Output

2078 · 5 marks

What is the use of get and getline functions? Explain with suitable example. [5]

Both get() and getline() are input functions in C++ used to read character(s) or strings from the input stream (cin). They are particularly useful when reading input that includes whitespace characters (spaces, tabs, newlines), which the standard operator cannot handle properly. --- The get() fun...

Open this answer on its own page →

2075 · 5 marks

How is character I/O different from Binary I/O? Explain with examples. [5]

--- Character I/O (also called Text Mode I/O) deals with data as a sequence of human-readable characters. Data is stored and read in ASCII/text format. - Uses functions like get(), put(), getline(), , << - Data is converted to/from text representation - Newline characters (\n) may be translated d...

Open this answer on its own page →

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]

A stream is a sequence of bytes flowing between a program and an input/output device (such as a keyboard, monitor, or file). In C++, a stream acts as an interface between the program and the actual I/O device, allowing data to flow in or out. We have been using the iostream standard library, whic...

Open this answer on its own page →

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]

Ofstream is used to write information to a file, and ifstream is used to read information from a file. The header <fstream must be included. After reading all employee records back from the file, we sort them by salary in ascending order before displaying. --- --- --- Step Operation Stream Used -...

Open this answer on its own page →

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]

In C++, the read() and write() member functions of file stream classes are used for reading and writing objects (binary data) to/from files or streams. Used to write an object (block of bytes) to a stream. Syntax: - (char ) casts the object address to a character pointer - sizeof(objectName) dete...

Open this answer on its own page →