Thursday, 14 May 2026

Structures and File Operations in C++

Structures and File Operations in C++
It has already been stated that a structure is a user-defined data type whose elements are heterogeneous types. This section lays emphasis on how a structure data can be read and written from a specified file. An array of structures can be stored and accessed using file handling commands. Sometimes, it may be required to store collective structure elements and retrieve them in the similar format. The following program segment illustrates how a file is opened for reading and writing a structure data type.

Example 1.
A program to read a data for the structure elements such as name, age, sex, height and weight from the keyboard and to store them on a specified file using read () and write () member functions. Again, the same file is opened for reading and displaying the contents of the file on the screen. 

// structures and le operations
#include <iostream>
#include <iomanip>
#include <fstream>
const int MAX = 200;
using namespace std;
struct school {
char name[20];
int age;
char sex;
oat height;
oat weight;
};
int main()
{
struct school student[MAX];
fstream in le;
char fname[10];
int i,n;
cout << “ enter a le name to be stored ? \n”;
cin >> fname;
in le.open(fname, ios:: in | ios::out);
// reading from the keyboard
cout << “ How many records are to be stored ? \n”;
cin >> n;
cout << “ enter the following information \n”;
for ( i=0; i<= n-1; ++i) {
cout << “ name : ” ;
cin >> student[i].name;
cout << “ age : ”;
cin >> student[i].age;
cout << “ sex : ”;
cin >> student[i].sex;
cout << “ height : ”;
cin >> student[i].height;
cout << “ weight : ”;
cin >> student[i].weight;
}
// storing onto the le
in le.open(fname, ios::out);
cout << “ storing onto the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.write ((char*) &student[i],sizeof(student[i]));
}
in le.close();
// reading from the le
in le.open(fname, ios::in);
cout << “ reading from the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.read ((char*) &student[i],sizeof(student[i]));
cout << student[i].name << setw(5) << student[i].age
<< setw(10) << student[i].sex << setw(5) <<
student[i].height << setw(5) << student[i].weight
<< endl;
}
in le.close();
return 0;
}
Output of the above program
enter a le name to be stored?
data
How many records are to be stored?
2
enter the following information
name: Antony
age: 23
sex: M
height: 167
weight: 56
name: Velusamy
age: 22
sex: M
height: 178
weight: 67
storing onto the le......
reading from the le......
Antony 23 M 167 56
Velusamy 22 M 178 67

ARRAY OF CLASS OBJECTS AND FILE OPERATIONS
It is well known that an array is a user-defined data type whose elements are homogeneous and stored in consecutive memory locations. For practical applications, an array of class objects are essential to construct complex data base systems and hence it is meaningful to study how an array of class objects are read and written on a file. The following program segment illustrates how to read and write an array of class objects from a file.

#include <fstream>
using namespace std;
int const max = 200;
class employee_info {
protected:
char name[20];
int age;
public:
void getdata();
void display();
};
int main()
{
student_info obj[max];
fstream in le;
in le.open( “data”, ios:: in | ios::out);
// storing onto the le
in le.open(fname, ios::out);
-------
-------
cout << “ storing onto the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.write ((char*) &obj[i],sizeof(obj[i]));
}
-------
-------
// reading from the le
in le.open(fname, ios::in);
cout << “ reading from the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.read ((char*) &obj[i],sizeof(obj[i]));
obj[i].display();
}
in le.close();
}

Example 1.
A program to read an array of class object of student_info such as name, age, sex, height and weight from the keyboard and to store them on a specified file using read () and write () member functions. Again, the same file is opened for reading and displaying the contents of the file on the screen.

// array of class objects and le operations
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX = 200;
class student_info {
protected:
char name[20];
int age;
char sex;
oat height;
oat weight;
public:
void getdata();
void display();
};
void student_info :: getdata()
{
cout << “ name:”;
cin >> name;
cout << “ age:”;
cin >> age;
cout << “ sex:”;
cin >> sex;
cout << “ Height:”;
cin >> height ;
cout << “ Weight:”;
cin >> weight;
}
void student_info :: display()
{
cout << name << setw(5) << age << setw(10) << sex
<< setw(5) << height << setw(5) << weight << endl;
}
int main()
{
student_info obj[MAX];
fstream in le;
char fname[10];
int i,n;
cout << “ enter a le name to be stored ? \n”;
cin >> fname;
in le.open(fname, ios:: in | ios::out);
cout << “ How many objects are to be stored ? \n”;
cin >>n;
// reading from the keyboard
cout << “ Enter the following information \n”;
for (i =0; i <= n-1; ++i) {
int j = i;
cout << endl;
cout << “ object = ” << j+1 << endl;
obj[i].getdata();
}
// storing onto the le
in le.open(fname, ios::out);
cout << “ storing onto the le......\n”;
for (i=0; i<=n-1; ++i){
in le.write ((char*) &obj[i],sizeof(obj[i]));
}
in le.close();
// reading from the le
in le.open(fname, ios::in);
cout << “ reading from the le......\n”;
for (i=0; i<=n-1; ++i){
in le.read ((char*) &obj[i],sizeof(obj[i]));
obj[i].display();
}
in le.close();
return 0;
}
Output of the above program
enter a le name to be stored?
data
How many objects are to be stored?
2
Enter the following information
object = 1
name: Madasamy.K
age: 24
sex: M
Height: 189
Weight: 90
object = 2
name: Mary.L
age: 22
sex: F
Height: 156
Weight: 45
storing onto the le......
reading from the le......
Madasamy.K 24 M 189 90
Mary.L 22 F 156 45

NESTED CLASSES AND FILE OPERATIONS
When a class is declared as a member of another class, then it is called as a nested class or a class within class. When a class is declared as a member of another class, it contains only the scoping of another class. The object of the outer class does not contain the object of the inner class. In this section, the reading and writing of the nested class objects from a file is described in detail. The following program segment illustrates how to read and write a nested class of objects from a file.

// array of nested class objects using le operations
#include <fstream>
using namespace std;
class student_info {
private:
char name[20];
public:
void getbase();
void display();
class date {
private:
int year;
public:
void getdate();
void show_date();
class age_class {
private:
int age;
public:
void getage ();
void show_age();
}; // end of age_class;
}; // end of date class
};// end of student_info class declaration
int main()
{
student_info obj1;
student_info::date obj2;
student_info::date::age_class obj3;
fstream in le;
in le.open(fname, ios:: in | ios::out);
-------
-------
// storing onto the le
in le.open(fname, ios::out);
cout << “ storing onto the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.write ((char*) &obj1,sizeof(obj1));
in le.write ((char*) &obj2,sizeof(obj2));
in le.write ((char*) &obj3,sizeof(obj3));
}
in le.close();
-------
-------
// reading from the le
in le.open(fname, ios::in);
cout << “ reading from the le......\n”;
for (i=0; i<=n-1; ++i ){
in le.read ((char*) &obj1,sizeof(obj1));
in le.read ((char*) &obj2,sizeof(obj2));
in le.read ((char*) &obj3,sizeof(obj3));
obj1.display();
obj2.show_date();
obj3.show_age();
}
in le.close();
}

Example 1.
A program to demonstrate how to read data from an array of nested class objects from the keyboard and to write it in a specified file.

// array of nested class objects using le operations
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX = 100;
class student_info {
private:
char name[20];
long int rollno;
char sex;
public:
void getbase();
void display();
class date {
private:
int day;
int month;
int year;
public:
void getdate();
void show_date();
class age_class {
private:
int age;
public:
void getage ();
void show_age();
}; // end of age_class;
}; // end of date class declaration
};// end of student_info class declaration
void student_info :: getbase()
{
cout << “ enter a name: ”;
cin >> name;
cout << “ roll no:”;
cin >> rollno;
cout << “ sex:”;
cin >> sex;
}
void student_info::date :: getdate()
{
cout << “ enter a date of birth\n”;
cout << “ day:”;
cin >> day;
cout << “ month:”;
cin >> month;
cout << “ year:”;
cin >> year;
}
void student_info::date ::age_class:: getage ()
{
cout << “ enter an age:”;
cin >>age;
}
void student_info:: display()
{
cout << name << “ ” <<‘\t’;
cout << rollno << “ ”;
cout << sex << “ ”;
}
void student_info::date::show_date()
{
cout << day << ‘/’ << month << ‘/’ << year << ‘\t’;
}
void student_info::date::age_class::show_age()
{
cout << ‘\t’<< age << endl;
}
int main()
{
student_info obj1[MAX];
student_info::date obj2[MAX];
student_info::date::age_class obj3[MAX];
int n,i;
fstream in le;
char fname[10];
cout << “ enter a le name to be stored ? \n”;
cin >> fname;
in le.open(fname, ios:: in | ios::out);
cout << “ how many students ?\n”;
cin >> n;
// reading from the keyboard
cout << “ enter the following information \n”;
for (i=0; i<= n-1; ++i) {
int j = i+1;
cout << “ \n object : ” << j << endl;
obj1[i].getbase();
obj2[i].getdate();
obj3[i].getage();
}
// storing onto the le
in le.open(fname, ios::out);
cout << “ storing onto the le......\n”;
for (i=0; i<=n-1; ++i){
in le.write ((char*) &obj1[i],sizeof(obj1[i]));
in le.write ((char*) &obj2[i],sizeof(obj2[i]));
in le.write ((char*) &obj3[i],sizeof(obj3[i]));
}
in le.close();
// reading from the le
in le.open(fname, ios::in);
cout << “ reading from the le......\n”;
cout << “\n\n\n” << endl;
cout << “ Contents of the array of nested classes \n”;
cout << “ ---------------------------------------------------\n”;
cout << “ student’s_name Roll_no sex date_of_birth age \n”;
cout << “ ---------------------------------------------------\n”;
for (i=0; i<=n-1; ++i){
in le.read ((char*) &obj1[i],sizeof(obj1[i]));
in le.read ((char*) &obj2[i],sizeof(obj2[i]));
in le.read ((char*) &obj3[i],sizeof(obj3[i]));
obj1[i].display();
obj2[i].show_date();
obj3[i].show_age();
}
cout << “ ---------------------------------------------------\n”;
in le.close();
return 0;
}
Output of the above program
enter a le name to be stored?
data
how many students?
3
enter the following information
object: 1
enter a name: Antony
roll no: 27001
sex: M
enter a date of birth
day: 21
month: 12
year: 1980
enter an age: 26
object: 2
enter a name: Ahmed.M
roll no: 27002
sex: M
enter a date of birth
day: 12
month: 11
year: 1981
enter an age: 25
object: 3
enter a name: Kuppusamy
roll no: 27004
sex: M
enter a date of birth
day: 10
month: 7
year: 1981
enter an age: 25
storing onto the le......
reading from the le......
Contents of the array of nested classes
--------------------------------------------------------––
student’s_name Roll_no sex date_of_birth age
--------------------------------------------------------––
Antony 27001 M 21/12/1980 26
Ahmed.M 27002 M 12/11/1981 25
Kuppusamy 27004 M 10/7/1981 25
--------------------------------------------------------––

RANDOM ACCESS FILE PROCESSING
    A sequential access file is very easy to create than a random access file. In the sequential access file, data are stored and retrieved one after another. The file pointer always move from the starting of the file to the end of file. On the other hand, a random access file need not necessarily start from the beginning of the file and move towards end of the file. Random access means moving the file pointer directly to any location in the file instead of moving it sequentially. The random access approach is often used with data base files. 

    In order to perform both reading and modifying an object of a data base, a file should be opened with mode of access for both to read and to write. The header file < fstream> is required to declare a random access file. As stated in the previous section that fstream is a class which is based on both the classes of ifstream and ofstream. The fstream inherits two file pointers, one for the input buffer and the other for the output buffer for handling a random access file both for reading and writing. Declaring a Random Access File The random access file must be opened with the following mode of access:

Mode of Access     Meaning
ios:: in                         in order to read a file
ios:: out                       in order to write a file
ios:: ate                        in order to append
ios:: binary                 binary format

The following program segment shows how a random access file is opened for both reading and writing.

#include <fstream>
using namespace std;
int main()
{
fstream le;
le.open(fname, ios:: in | ios:: out | ios:: ate | ios:: binary);
-------
-------
}
It is essential to open a random access file with the following mode of access in order to perform read, write and append. The file should be declared as a binary status as the data members of a class is stored in a binary format. The fstream inherits the following member functions in order to move the file pointer in and around the data base.

Enumerated Value          File Position
ios::beg                                    from the beginning of the file
ios::cur                                    from the current file pointer position
ios::end                                   from the end of the file

The following member functions are used to process a random access file.
(a) seekg(): The seekg() member function is used to position file operations for random input operations. For example, the following program segment shows the positioning of the file operation for a random access file

#include <fstream>
using namespace std;
int main()
{
fstream in le;
-------
-------
in le.seekg(40); // goto byte number 40
in le.seekg(40,ios::beg); // same as the above
in le.seekg(0,ios::end); // goto the end of le
in le.seekg(0); // goto start of the le
in le.seekg(-1, ios::cur); // the le pointer is moved
// back end by one byte
}
(b) seekp(): The seekp() member function is used to position file operations for random output operations.
(c) tellg(): The tellg() member function is used to check the current position of the input stream.
(d) tellp(): The tellp() member function is used to check the current position of the output stream.

Example 1.
A program to demonstrate how to read a character from a random access file using seekg() method.

//reading from the le
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream in le;
char fname[20];
char ch;
cout << “enter a le name ?\n”;
cin >> fname;
in le.open(fname, ios::in | ios :: out);
in le.seekg(5L,ios::beg);
in le.get(ch);
cout << “after 5 characters from beginning = ” << ch;
cout << ‘\n’;
in le.seekg(-10L,ios::end);
in le.get(ch);
cout << “10 characters before end = ” << ch;
cout << ‘\n’;
in le.seekg(0,ios::cur);
in le.get(ch);
cout << “current character = ” << ch;
in le.close();
return 0;
}
Output of the above program
The file called “data.txt” consists of the following contents:
abcdefghijklmnopqrstuvwxyz
enter a le name?
data.txt
after 5 characters from beginning = f
10 characters before end = r
current character = s

Example 2.
A program to read a class object of student_info such as name, roll number, sex, age, height and weight from the keyboard and to store them on a specified file using write() member functions.

//storing records into the random access le
#include <iostream>
#include <fstream>
using namespace std;
struct student_info {
char name[25];
long int rollnumber;
char sex;
int age;
oat height;
oat weight;
};
int main()
{
fstream in le;
student_info obj[100];
char fname[20];
int n;
cout << “enter a le name ?\n”;
cin >> fname;
in le.open(fname, ios::out | ios :: binary);
if (!in le)
{
cout << “Error in opening le \n”;
return 0;
}
cout << “ How many records ? \n”;
cin >> n;
for (int i = 0; i <= n-1; ++i) {
cout << “ Name : \n”;
cin >> obj[i].name;
cout << “ Roll Number : \n”;
cin >> obj[i].rollnumber;
cout << “ Sex : \n”;
cin >> obj[i].sex;
cout << “ Age : \n”;
cin >> obj[i].age;
cout << “ Height : \n”;
cin >> obj[i].height;
cout << “ Weight : \n”;
cin >> obj[i].weight;
}
cout << “ storing data onto the le ...\n”;
for (int i = 0; i <= n-1; ++ i) {
in le.write((char *) &obj[i],sizeof(obj[i]));
}
in le.close();
return 0;
}
Output of the above program
enter a le name?
data
How many records?
1
Name : Velusamy
Roll Number : 27001
Sex : M
Age : 24
Height : 167
Weight : 65
storing data onto the le ...

Example 3.
A program to demonstrate how to read a class object of student_info such as name, roll number, sex, age, height and weight from a random access file using seekg() method.

//reading records from the random access le
#include <iostream>
#include <fstream>
using namespace std;
struct student_info {
char name[25];
long int rollnumber;
char sex;
int age;
oat height;
oat weight;
};
//function prototype
long bytesize(int recordnumber);
void display (student_info obj);
int main()
{
fstream in le;
student_info obj;
char fname[20];
char ch;
cout << “enter a le name ?\n”;
cin >> fname;
in le.open(fname, ios::in | ios :: binary);
if (!in le)
{
cout << “Error in opening le \n”;
return 0;
}
cout << “The rst Record : ” << ‘\n’;
in le.seekg(bytesize(0),ios::beg);
in le.read((char *) &obj,sizeof(obj));
display(obj);
cout << “The second Record : ” << ‘\n’;
in le.seekg(bytesize(1),ios::beg);
in le.read((char *) &obj,sizeof(obj));
display(obj);
cout << “The Last Record : ” << ‘\n’;
in le.seekg(bytesize(-1),ios::end);
in le.read((char *) &obj,sizeof(obj));
display(obj);
in le.close();
return 0;
}
long bytesize(int recordnumber)
{
return (sizeof(student_info) *recordnumber);
}
void display(student_info obj)
{
cout << “Name :” << obj.name << ‘\n’;
cout << “Roll Number:” << obj.rollnumber;
cout << ‘\n’;
cout << “Sex :” << obj.sex << ‘\n’;
cout << “Age :” << obj.age << ‘\n’;
cout << “Height :” << obj.height << ‘\n’;
cout << “Weight :” << obj.weight << ‘\n’;
}
Output of the above program
enter a le name?
data
The rst Record:
Name : Ravich
Roll Number : 27001
Sex : M
Age : 21
Height : 167
Weight : 78
The second Record:
Name : Ahmed
Roll Number : 27002
Sex : M
Age : 23
Height : 145
Weight : 67
The Last Record:
Name : Antony
Roll Number : 27004
Sex : M
Age : 22
Height : 182
Weight : 89

0 comments

Post a Comment