Updating Files in C++

You can update a binary file by opening a file using the mode ios: :in | ios: out | ios::binary.

Often you need to update the contents of the file. You can open a file for both input and output. For example,

binaryio.open(“student.dat”, ios::in | ios::out | ios::binary);

This statement opens the binary file student.dat for both input and output.

Listing 13.19 demonstrates how to update a file. Suppose file student.dat already has been created with ten Student objects from Listing 13.18. The program first reads the second stu­dent from the file, changes the last name, writes the revised object back to the file, and reads the new object back from the file.

Listing 13.19 UpdateFile.cpp

1 #include <iostream>
2
#include <fstream>
3
#include “Student.h”
4 using namespace std;
5
6
void displayStudent(const Student& student)
7 {
8     cout << student.getFirstName() <<
” “;
9     cout << student.getMi() <<
” “;
10    cout << student.getLastName() <<
” “;
11    cout << student.getScore() << endl;
12 }
13
14
int main()

15 {
16    fstream binaryio;
// Create stream object
17
18   
// Open file for input and output
19    binaryio.open(“student.dat”, ios::in | ios::out | ios::binary);
20
21    Student student1;
22    binaryio.seekg(
sizeof(Student));
23    binaryio.read(
reinterpret_cast<char*>
24    (&student1),
sizeof(Student));
25    displayStudent(student1);
26
27    student1.setLastName(
“Yao”);
28    binaryio.seekp(
sizeof(Student));
29    binaryio.write(
reinterpret_cast<char*>
30    (&student1),
sizeof(Student));
31
32    Student student2;
33    binaryio.seekg(
sizeof(Student));
34    binaryio.read(
reinterpret_cast<char*>
35    (&student2),
sizeof(Student));
36    displayStudent(student2);
37
38    binaryio.close();
39
40   
return 0;
41 }

The program creates a stream object in line 16 and opens the file student.dat for binary input and output in line 19.

The program moves to the second student in the file (line 22) and reads the student (lines 23-24), displays it (line 25), changes its last name (line 27), and writes the revised object back to the file (lines 29-30).

The program then moves to the second student in the file again (line 33) and reads the stu­dent (lines 34-35) and displays it (line 36). You will see that the last name of this object has been changed in the sample output.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *