C++ File Streams, Binary I/O & Random Access File Pointers
Idea in plain words
Stream Classes in : ifstream (input), ofstream (output), fstream (input/output).
Exam tip
High-yield exam topic (Very High).
Explanation
C++ stream architecture treats files as sequences of continuous bytes. Binary file I/O bypasses character conversion overhead, persisting in-memory objects directly to storage. Random access operations move the file read/write cursor via seekg/seekp with offsets ios::beg, ios::cur, or ios::end, enabling direct record indexing.
Key points
- File Open Modes: ios::in (read), ios::out (write/overwrite), ios::app (append), ios::binary (binary I/O), ios::ate (seek to end on open).
- Binary File I/O: read((char*)&obj, sizeof(obj)) and write((char*)&obj, sizeof(obj)) read/write raw memory byte buffers.
- File Pointers: get pointer (seekg to seek, tellg to get position); put pointer (seekp to seek, tellp to get position).
- Stream Status Flags: eof() (end of file), fail() (format error), bad() (hardware error), good() (healthy).
Example
Example
To seek to the 5th record: file.seekg(4 * sizeof(StudentRecord), ios::beg).
Code examples
// Writing and Reading Class Objects to Binary Files in C++
#include <iostream>
#include <fstream>
using namespace std;
class StudentRecord {
public:
int id;
char name[30];
float gpa;
void input(int i, const char* n, float g) {
id = i;
strncpy(name, n, 29);
name[29] = '\0';
gpa = g;
}
};
void saveRecord(const StudentRecord& s) {
ofstream outFile("students.dat", ios::binary | ios::app);
outFile.write(reinterpret_cast<const char*>(&s), sizeof(s));
outFile.close();
}
void readAllRecords() {
ifstream inFile("students.dat", ios::binary);
StudentRecord s;
while (inFile.read(reinterpret_cast<char*>(&s), sizeof(s))) {
cout << "ID: " << s.id << ", Name: " << s.name << ", GPA: " << s.gpa << endl;
}
inFile.close();
}
Exam questions
- [8 Marks] Write a complete C++ program to store student records (roll, name, marks) in a binary file and search for a record by roll number using read() and seekg().
- [7 Marks] Explain file opening modes and the functions of seekg(), seekp(), tellg(), and tellp().