Unit V – File Operations (OOP in C++)
5.1 C++ Stream Classes & File Stream Classes
Stream means a flow of data between program and file/device. C++ uses streams to perform input and
output operations. Types of Streams: 1. Input Stream: Used for reading data (e.g., cin, ifstream) 2.
Output Stream: Used for writing data (e.g., cout, ofstream) Important Stream Classes in C++:
Class Purpose Header File
ios Base class for all stream classes <iostream>
istream For input operations <iostream>
ostream For output operations <iostream>
ifstream For input from file <fstream>
ofstream For output to file <fstream>
fstream For both input/output to file <fstream>
5.2 Detection of End of File (EOF) & File Modes
End of File (EOF) means no more data is available for reading from the file. Detected using
while(![Link]()) or by checking if file read fails.
Example: #include #include using namespace std; int main() { ifstream fin("[Link]"); string line;
while(![Link]()) { getline(fin, line); cout << line << endl; } [Link](); }
File Modes define how a file is opened.
Mode Meaning
ios::in Open file for reading
ios::out Open file for writing
ios::app Append data to end of file
ios::ate Open file and move to end immediately
ios::trunc Delete previous data in file
ios::binary Open file in binary mode
Example: fstream file("[Link]", ios::in | ios::out);
5.3 Opening, Closing, Reading, Writing Files
Files can be opened in two ways:
1. Using Constructor:
ifstream fin("[Link]");
ofstream fout("[Link]");
2. Using open() Function:
fstream file;
[Link]("[Link]", ios::out);
Always close files after operations:
[Link]();
Reading from File: ifstream fin("[Link]"); string line; while(getline(fin, line)) { cout << line << endl; }
[Link](); Writing to File: ofstream fout("[Link]"); fout << "Hello Students!" << endl; [Link]();
Formatted I/O in File Example: #include fout << setw(10) << "RollNo" << setw(15) << "Name" << endl;
5.4 Types of File Access
1. Sequential Access
- Data is read/written in sequence (from start to end).
- Example: reading a text file line by line.
- Slower for large files but simple to use.
2. Random Access
- Data can be read/written at any position in the file.
- Uses seekg(pos), seekp(pos), tellg(), tellp().
Example: fstream file("[Link]", ios::in | ios::out); [Link](10); // Move to 10th byte char ch; file >> ch;
cout << ch; [Link]();
Summary
Concept Description
Stream Flow of data between program and device
ifstream, ofstream, fstream Classes for file handling
EOF Indicates end of file
File Modes Define how a file is opened
Sequential Access Read/write in order
Random Access Jump to any location in file