You are on page 1of 32

File Handling

----------------------
File handling is used for store a data permanently in computer. Using file handling we can store our data
in secondary memory (Hard disk).

How to achieve the File Handling

For achieving file handling we need to follow the following steps:-

 Naming a file
 Opening a file
 Writing data into the file
 Reading data from the file
 Closing a file.

Streams in C++
We give input to the executing program and the execution program gives back the output. The sequence
of bytes given as input to the executing program and the sequence of bytes that comes as output from the
executing program are called stream. In other words, streams are nothing but the flow of data in a
sequence of bytes.

Keyboard Monitor

Input Stream Output Stream

Console Input output operation

RAM

Input Stream (Ifstream)

Output Stream(ofstream)
Stud.doc FILE

File Input Output operation

Fig: Console Program File Interaction

Classes for File stream operations


The I/O system of C++ contains a set of classes that define the file handling methods. These include
ifstream, ofstream and fstream classes. These classes area derived from fstream and from the
corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream
and therefore we must include this file in any program that uses files.

ios

iostream file

istream streambuf ostream

iostream
-----------------------------------------------------------------------------------------------------------------------------------

ifstream fstream ofstream filebuf

fstream file
fstreambase

Fig: stream classes for file operations

ios
 This class is the base class for other classes in this class hierarchy.
 This class contains the necessary facilities that are used by all the other derived classes for
input and output operations.

istream
 This class is derived from the class ‘ios’.
 This class handle input stream.
 The extraction operator(>>) is overloaded in this class to handle input streams from files to
the program execution.
 This class declares input functions such as get(), getline() and read().
ostream
 This class is derived from the class ‘ios’.
 This class handle output stream.
 The insertion operator(<<) is overloaded in this class to handle output streams to files from
the program execution.
 This class declares output functions such as put() and write().

streambuf
 This class contains a pointer which points to the buffer which is used to manage the input
and output streams.

fstreambase
 This class provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream class.
 This class contains open() and close() function.

ifstream
 This class provides input operations.
 It contains open() function with default input mode.
 Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.

ofstream
 This class provides output operations.
 It contains open() function with default output mode.
 Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.

fstream
 This class provides support for simultaneous input and output operations.
 Inherits all the functions from istream and ostream classes through iostream.

filebuf
 Its purpose is to set the file buffers to read and write.
Opening and closing a File
------------------------------------------

If we want to use a disk file, we need to decide the following things about the file and its intended
use:
1. Suitable name for the file
2. Data type and structure
3. Purpose
4. Opening method

The file name is a string of characters that make up a valid file name for the operating system. It
may contain two parts, a primary name and an optional period with extension.

Eg:
Student.doc
Item.txt

For opening a file, we must first create a file stream and then link it to the file name. A file stream
can be defined using the class’s ifstream, ofstream and fstream. The class to be used depends upon
the purpose i.e. whether we want to read data from the file or write data to it.

A file can be opened in two ways-

1. Using the constructor function of the class.


2. Using the member function open() of the class.

Note: The first method is useful when we use only one file in the stream. The second method is used
when we want to manage multiple files using one stream.

Opening files using constructor


------------------------------------------
Constructor is used to initialize an object while it is being created. Filename is used to initialize the
stream object. This involves the following steps—

1. Create a file stream object to manage the stream using the appropriate class. That is the
class ofstream is used to create the output stream and the class ifstream is used to create
input stream.
2. Initialize the file object with the desired file name
Eg:

File_stream_class <stream-object>(“file-name”);

ofstream fout(“student.doc”);

This create “fout” as an ofstream object that manages the output stream. The object can be
any valid C++ name such as o_file, myfile, outfile etc. This statement opens the file
“student.doc” and attaches it to the output stream “fout”.
Similarly, the following statements declares “fin” as an ifstream object and attaches it to the
file “student.doc” for reading.

Eg:
ifstream fin(“student.doc”);

The connection with a file is closed automatically when the stream object expires mean when the
program terminates.

Program 1 put data

fout Student file

Program 2 get data


fin

Fig: Two file streams working on one file

Q: WA C++ file handling program to write data into the file called student.doc

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

ofstream fout("d:/student.doc");

fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student

fout.close();

return 0;
}

Q: WA C++ file handling program to read data from the file called student.doc

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];

ifstream fin("d:/student.doc");

fin>>rno>>name>>fee; //read data from the file student

fin.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}

Q: write a single file handling program in c++ to reading and writing data on a file.

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

ofstream fout("d:/student.doc");

fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student

fout.close();
ifstream fin("d:/student.doc");

fin>>rno>>name>>fee; //read data from the file student

fin.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}
Opening file using member function open()
---------------------------------------------------------

The function open() can be used to open multiple files that use the same stream object.

Syntax:
file_stream_class <stream-object>;

stream-object.open(“file-name”);

Q: WA C++ program to write data into the file called student.doc using member function open().

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

ofstream fout;
fout.open("d:/student.doc");

fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student

fout.close();

return 0;
}
Q: WA C++ program to read data from the file called student.doc using member function open().

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];

ifstream fin;
fin.open("d:/student.doc");

fin>>rno>>name>>fee; //read data from the file student

fin.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}

Q: write a single program in c++ to reading and writing data on a file using member function
open().

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

ofstream fout;
fout.open("d:/student.doc");

fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student

fout.close();

ifstream fin;
fin.open("d:/student.doc");
fin>>rno>>name>>fee; //read data from the file student

fin.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}

The function open() can be used to open multiple files that use the same stream object.

Q: Write a C++ program to open multiple files for writing and reading purpose. Use open()
function.

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];

//enter the student details


cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Student Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

int eid,salary;
char ename[50];

//enter employee details


cout<<"\nEnter the Employee Id:";
cin>>eid;
cout<<"\nEnter the Employee Name:";
cin>>ename;
cout<<"\nEnter the Salary:";
cin>>salary;

ofstream fout;
fout.open("d:/student.doc");
fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
fout.close();

fout.open("d:/employee.doc");
fout<<eid<<"\t"<<ename<<"\t"<<salary;
fout.close();

ifstream fin;
fin.open("d:/student.doc");
fin>>rno>>name>>fee; //read data from the file student
fin.close();

cout<<endl<<"Roll-NO\tName\tFee";
cout<<endl<<endl<<"-----------------------------";
cout<<endl<<endl<<rno<<"\t"<<name<<"\t"<<fee;

fin.open("d:/employee.doc");
fin>>eid>>ename>>salary; //read data from the file student
fin.close();

cout<<endl<<endl<<"EMP-ID\tName\tSalary";
cout<<endl<<"-----------------------------";
cout<<endl<<endl<<eid<<"\t"<<ename<<"\t"<<salary;

return 0;
}
File Opening modes
---------------------------
We have used “ifstream” and “ofstream” constructor and member function open() to create new files as
well as to open the existing files. In both these methods, we used to only one argument that was the file-
name.

However these functions can take two arguments, the first argument is file-name and second argument for
specifying the file-mode.

Syntax :

stream-object.open(“file-name”, mode);

The second argument “mode” called file mode parameter specifies the purpose for which the file is
opened.

The prototype of these class member functions contains default values for the second argument and
therefore they use the default values in the absence of the actual values.

The default values are as follows:

ios::in  for ifstream function

ios::out  for ofstream function

List of file mode parameter


------------------------------------
Parameter Meaning

ios::app Append to end of file

ios::ate Go to the end of file on opening

ios::binary Binary file

ios::in Opening file for reading only

ios::out Opening file for writing only

ios::trunc Delete the contents of file if it exists

ios::nocreate Open fails if the file does not exist

ios::noreplace Open fails if the file already exist

Note:

1. Opening a file in ios::out mode also open it in the ios::trunc mode by default.
2. Both ios::app and ios::ate take us to the end the file when it is opened. The difference between the
two parameters is that the ios::app allows to add data to the end of the file only, while ios::ate
mode permits us to add data or to modify existing data anywhere in the file. In both the cases, a
file is created by the specified name, if it does not exist.

3. Creating a stream using ifstream implies input and creating a stream using ofstream implies
output. So in these cases it is not necessary to provide the mode parameter.

4. The fstream class does not provide a mode by default and therefore, we must provide the mode
explicitly when using an object of fstream class.

5. The mode can combine two or more parameters using the bitwise OR operator.

Eg:

fout.open(“student.doc”, ios::app | ios::nocreate);

Q: WA C++ program to read and write from the file called student.doc. Use fstream class and
member function open() .
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;

fstream file;
file.open("d:/student.doc",ios::out);
file<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
file.close();

file.open("d:/student.doc",ios::in);
file>>rno>>name>>fee; //read data from the file student
file.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}

Checking for errors


----------------------------
When the user attempts to read file that does not exists or opens a read only file for writing purpose, in
such situation operation fails. Such errors must be reported and proper actions have to be taken before
further operation.

The !(logical negation operator) is useful for detecting the errors. It is a unary operator and in short it is
called as not operator. The not operator can be used with object of stream class. This operator returns non-
zero value if stream errors are found during operation.

Q: Write a program to check whether the file is successfully opened or not.

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
int rno,fee;
char name[50];
char fname[50];

cout<<"\nEnter the File Name:";


cin>>fname;

fstream file;
file.open(fname,ios::in);

if(!file)
{
cout<<"\nError in opening file:\t"<<fname;
getch();
}

file>>rno>>name>>fee; //read data from the file student

file.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}

Finding end of a file


---------------------------
While reading a data from a file, it is necessary to find whether the file end i.e end of the file. The
programmer cannot predict the end of a file. In a program while reading the file, if the program does not
detect the end of the file, the program drops in an infinite loop.

To avoid this, it is necessary to provide correct instruction to the program that detects the end of file. Thus
the end of file is detected; the process of reading data can be easily terminated.

The eof() member function is used for this purpose. The eof() stands for end of file. The eof() function
returns non-zero value when end of file is detected, otherwise zero.

Q: Write a C++ program to read and display the content of file. Use eof() member function.

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{

char ch;

fstream file;
file.open("d:/student.doc",ios::in);

if(!file)
{
cout<<"\nError in opening file:\t"<<"student.doc";
getch();
}

while(file.eof()==0)
{ // function get() reads a single character from the associated stream.

file.get(ch); // or ch=file.get();
cout<<ch;
}

file.close();

return 0;
}

Write a program to detect end of the file using function eof(). Display the values returned by the
eof()function.

Q: Write a C++ program to count the number of words and lines in a file.

#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];

ifstream fin;
fin.open("e:/str.doc");

if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int word=0,line=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{

ch=fin.get();
if(ch==' ')
word++;
if(ch=='\n')
line++;
cout<<ch;
}

cout<<"\nTotal Word:"<<word;
cout<<"\nTotal Line:"<<line;

fin.close();
return 0;
}

Q: Write a C++ program to count the number of alphabets, digit and spaces present in a file.

#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];
cout<<"Enter the String:";
gets(str);

ofstream fout;
fout.open("e:/str1.doc");
int i;

for(i=0;str[i]!='\0';i++)
fout.put(str[i]);

fout.close();

ifstream fin;
fin.open("e:/str1.doc");

if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int a=0,d=0,s=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{

ch=fin.get();
i=ch;
if((i>=65 && i<=90)||(i>=97 && i<122))
a++;
if(i>=47 && i<=58)
d++;
if(ch==' ')
s++;
cout<<ch;
}

cout<<endl<<"No. OF Alphabates:"<<a;
cout<<endl<<"No. Of Digits:"<<d;
cout<<endl<<"No. Of Spaces:"<<s;
fin.close();
return 0;
}

Q: Write a C++ program to read data from a text file and then write in another text file.

int main()
{
ofstream fout(“sare1.txt”); //create a file to write
ifstream fin(“sare1.txt”);
fout<<“Hello India”;
fout.close(); //closing the file

fout.open(“sare2.txt”); //create file to write


char ch;
while(fin.eof()==0)
{
fin>>ch; //reading data from file
fout<<ch; //writing data to file
}
fin.close();
fout.close();

return 0;
}

File pointers and there manipulation


----------------------------------------------
Each file has two associated pointers known as file pointers. One of them is called the input pointer or get
pointer and other is called the output pointer or put pointer. We can use these pointers to move through
the files while reading and writing.
The input pointer is used for reading the contents of a given file location and the output pointer is used for
writing to a given file location.

Default Action
--------------------
When we open a file in read only mode, the input pointer is automatically set at the beginning so that we
can read the file from the start.

Similarly when we open a file in write only mode, the existing contents are deleted and the output pointer
is set at beginning.

This enables us to write to file from the start.

In case, we want to open an existing file to add more data, the file is opened in append mode. This moves
the output pointer to the end of the file.

“Demo” file

Open for read only M A N J E E T


Input pointer

Open for writing only M A N J E E T


Output pointer

Open in append mode M A N J E E T


(for writing more data) Output pointer

Fig: Action on file pointers while opening a file

File pointer manipulation function


-------------------------------------------
If the user wants to move the file pointers at desired locations in the file during run-time to perform
various operations. For this purpose, we have 4 file pointer manipulation functions. Among them 2 are
dedicated to “put” pointer and 2 are dedicated to “get” pointer.

Manjeet kumar

seekg()  This function moves the “get” pointer to a specified location to do a read operation.
tellg()  This function tells the current position of the “get” pointer in the file.

seekp()  This function moves the “put” pointer to a specified location to do a write operation.

tellp()  This function tells the current position of the “put” pointer in the file.

Eg:

ifstream fin(“temp.doc”);

fin.seekg(10);

Moves the file pointer to the byte number 10.

The bytes in a file are numbered beginning from zero. Therefore, the pointer will be pointing to the 11th
byte in the file.

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{

char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);

fout.close();

ifstream fin;
fin.open("d:/Demo.doc",ios::ate);

fin.seekg(7);// move 8 bytes from the beginning

while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;

}
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{

char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);

fout.close();

ifstream fin;
fin.open("d:/Demo.doc",ios::ate);

int x=fin.tellg();// tells the current position in the file

cout<<endl<<"Number of byte="<<x;
fin.close();
return 0;

On execution of this statement, the input pointer is moved to the end of the file “Demo.doc” and the value
of ‘x’ will represent the number of bytes in the file.
Specify the offset
----------------------
We have seen how to move a file pointer to desired location using the seek function. The argument to
these functions represents the absolute position in the file.

file

Start end

fin.seekg(m);

m bytes

file pointer

Fig: Action of single argument seek function

“seek” function seekg() and seekp() can also be used with two arguments as follows:

seekg(offset, refposition) ;

seekp(offset, refposition);

The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants defined
in the “ios” class.

1. ios::beg  start of the file

2. ios::cur  current position of the pointer

3. ios:end end of the file

seek call Action

fin.seekg(0, ios::beg); Go to start

fin.seekg(0, ios::cur); Stay at the current position

fin.seekg(0, ios::end); Go to the end of file

fin.seekg(m, ios::beg); Move to (m+1)th byte in a file

fin.seekg(m, ios::cur); Go forward by ‘m’ byte from the current position

fin.seekg( -m, ios::cur); Go backward by ‘m’ bytes form the current


position

fin.seekg( -m, ios::end); Go backward by ‘m’ bytes from the end.


Example:

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::in|ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);

fout.close();

ifstream fin;
fin.open("d:/Demo.doc");
fin.seekg(7,ios::beg); //move 8 bytes from the beg.
while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;

}
Q: Write a program to write text in the file. Read the text from the file from end of file. Display the
contents of file in reverse order.

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);

fout.close();

ifstream fin;
fin.open("d:/Demo.doc");
fin.seekg(0,ios::end); //move the cursor to the end of file

int m=fin.tellg();

for(i=1;i<=m;i++)
{
fin.seekg(-i,ios::end);
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;

}
Sequential input and output operation
------------------------------------------------
File stream classes support a number of member functions for performing the input and output operations
on files. One pair of functions, put() and get() are designed for handling a single character at a time.
Another pair of functions, write() and read() are designed to write and read blocks of binary data.

put() and get() functions


------------------------------

The function put() writes a single character to the associated stream. Similarly the function get() reads a
single character from the associated stream.

Example:

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::in|ios::out|ios::ate|ios::binary);

for(i=0;str[i]!='\0';i++)
fout.put(str[i]); //put a character to a file

fout.close();

ifstream fin;
fin.open("d:/Demo.doc");

while(fin.eof()==0)
{
ch=fin.get(); //get a character from a file
cout<<ch; //display it on screen
}
fin.close();
return 0;

}
write() and read() functions
----------------------------------

The functions write() and read(), unlike the function put() and get(), handle the data in binary form. This
means that the values are stored in the disk file in the same format in which they are stored in the internal
memory.

Example:

The ‘int’ value 2594 is stored in the binary and character format. The ‘int’ takes two bytes to store its
value in the binary format, irrespective of it’s size. But a 4 digit int value will take 4 bytes to store it in
character format.

2 bytes

Binary format 00001010 00100010

Character format 2 5 9 4

4 bytes

Fig - Binary and character format of an integer value.

The binary format is more accurate for storing the numbers as they are stored in the exact internal
representation. There are no conversions while saving the data and therefore saving is much faster.

The binary input and output functions take the following form:

file.read((char *)&v, sizeof(v));

file.write((char *)&v,sizeof(v));

These functions takes two argument, the first is the address of the variable ‘v’ and the second is the length
of that variable in bytes. The address of the variable must be cast to type char *(i.e. pointer to char).

#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout;
fout.open("d:/student.doc");
fout.write((char*)&rno,sizeof(rno));
fout.write((char*)&name,sizeof(name));
fout.write((char*)&fee,sizeof(fee));
fout.close();

ifstream fin;
fin.open("d:/student.doc");
fin.read((char*)&rno,sizeof(rno));
fin.read((char*)&name,sizeof(name));
fin.read((char*)&fee,sizeof(fee));
fin.close();

cout<<"\nRoll No:\t"<<rno<<endl;
cout<<"\nName:\t"<<name<<endl;
cout<<"\nFee:\t"<<fee<<endl;

return 0;
}

Reading and Writing a class object

#include<iostream>
#include<fstream>
using namespace std;
class Student
{
int rno,fee;
char name[50];
public:
void set_data()
{
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
}

void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};

main()
{
int i,no;
Student s[10];
cout<<"\nEnter Number of Student:";
cin>>no;

ofstream fout;
fout.open("d:/Student.doc");

cout<<"\nEnter the Student details one by one:";


for(i=0;i<no;i++)
{
s[i].set_data();
fout.write((char*)&s[i],sizeof(s[i]));
}
fout.close();

ifstream fin;
fin.open("d:/Student.doc");
if(!fin)
{
cout<<"\nFile not found.";
return 0;
}

for(i=0;i<no;i++)
{
fin.read((char*)&s[i],sizeof(s[i]));
s[i].display();
}

fin.close();
return 0;

}
Q. Create a class to specify data on students given below:

Roll number, Name, Department, and Course.

Write a menu driven program in C++ for following operations on student class such as Add,
Display all record, Search record by given roll number and Delete record by given roll number
from the file.

#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<fstream.h>
#include<stdio.h>

void deletedata(int);
void search(int);
class stud
{
public:
int rno;
char name[20];
public:
void getdata()
{
cout<<"\nEnter the rno:";
cin>>rno;
fflush(stdin);
cout<<"Enter the name:";
cin>>name;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<endl;
}

};
main()
{
int i,chk;
char chk1;
char ch;
stud s;
fstream file,temp;
clrscr();

ofstream fout1;
ifstream fin;
// fout.open("b.dat",ios::in|ios::out|ios::ate|ios::binary);
cout<<"\n1.ADD\n2.DISPLAY CURRENT RECORD\n3.UPDATE
RECORD\n4.DELETE\n5.SEARCH\n6.Exit";
while(1)
{
cout<<"\nEnter the choice";
cin>>chk;
switch(chk)
{
case 1:

cout<<"\nADD SUTUDENT DETAILS\n";


fout1.open("student.doc", ios::in|ios::out|ios::ate|ios::binary);
s.getdata();
fout1.write((char*)&s,sizeof(s));
fout1.close();

fin.open("student.doc");
if(!fin)
{
cout<<"Error in opening file.";
getch();
exit(0);
}
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;

case 2:
cout<<"\nCURRENT INFORMATION\n";
fin.open("student.doc",ios::in);
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;

case 3:
ofstream fout;
fout.open("student.doc", ios::in|ios::out|ios::ate|ios::binary);
if(!fout)
{
cout<<"Error in opening file.";
getch();
exit(0);
}
int last=fout.tellp();
int n=last/sizeof(s);

cout<<"\nTotal Number of Record:"<<n;

cout<<"\nEnter the record number to be updated:";


int obj;
cin>>obj;
int location=(obj-1)*sizeof(s);
fout.seekp(location);
//file.close();
// file.open("student.doc",ios::out|ios::ate);
cout<<"\nEnter the new record\n";
s.getdata();

fout.write((char*)&s,sizeof(s));
fout.close();

fin.open("student.doc");
fin.seekg(0);
cout<<"\n CONTENT OF THE UPDATED FILE\n";
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;

case 4:
int rno1;
cout<<"\nenter the rno to delete the record:";
cin>>rno1;
deletedata(rno1);
break;

case 5:
int rno2;
cout<<"\nEnter the rno to search:";
cin>>rno2;
search(rno2); break;
case 6: exit(0);

default: cout<<"\nEnter the Correct Choice!";


}

getch();

}
return 0;

void deletedata(int rno1)


{

stud s;

fstream file,temp;
file.open("student.doc",ios::in);
temp.open("temp_student.doc",ios::out);
file.seekg(0);
//while(!file.eof())
//{
while(file.read((char *)&s,sizeof(s)))
{
if(s.rno!=rno1)
temp.write((char *)&s,sizeof(s));
}
file.close();
temp.close();

file.open("student.doc",ios::out);
temp.open("temp_student.doc",ios::in);
temp.seekg(0);
//while(!temp.eof())
//{
while(temp.read((char *)&s,sizeof(s)))
{
//if(temp.eof())
// break;
file.write((char *)&s,sizeof(s));
}
file.close();
temp.close();
}

void search(int rno1)


{
ifstream file;
file.open("student.doc");
int rno;
stud s;
if(!file)
{
cout<<"Error in opening file.";
getch();
exit(0);
}
file.seekg(0);
while(file.read((char *)&s,sizeof(s)))
{
if(s.rno==rno1)
{
s.display();
//cout<<endl<<s.rno<<" "<<s.name;
}

}
file.close();
}

You might also like