Sunteți pe pagina 1din 30

Kensri School and College, Bengaluru

DATA FILE HANDLING


 INTRODUCTION
 A file is a collection of related data stored in a particular area on the disk.
 Programs can be designed to perform the read and write operations on these files.
 In general a file is a sequence of bits, bytes, lines or records whose meaning is defined by its
user.
 Streams: C++ I/O occurs in streams, which are sequence of bytes.
 If bytes flows from device like a keyboard, a disk drive, etc to main memory, this is called
Input operation.
 If bytes flow from main memory to devices like a display screen, a printer etc. this is called
Output operation.
 In C++, file input/output facilities are implemented through a header file fstream.h.

 File Stream :
 A stream is a general term used to name flow of data. Different streams are used to
represent different kinds of data flow.
 A stream is sequence of bytes. In C++, a stream is a general name given to flow of data.
 Different streams are used to represent different kinds of data flow.
 The three streams in C++ are as follows.
o Input Stream: The stream that supplies data to the program is known as input stream.
o Output Stream: The stream that receives data from the program is known as output
stream.
o Error Stream: Error streams basically an output stream used by the programs to the file
or on the monitor to report error messages.

 fstream.h header file:


 The I / O system of C++ contains a set of classes that define the file handling methods.
 These include ifstream, ofstream and fstream.
o ifstream: can be used for read operations.
o ofstream: can be used for write operations.
o fstream: can be used for both read & write operations.
 These classes are derived from fstream base and from the corresponding iostream.h.
 These classes, designed to manage the disk files, are declared in fstream.h and therefore we
must include this file in any program that uses files.

Computer Science 1 Class 12/PU-II


Kensri School and College, Bengaluru

 Classes for file stream operation:


Class Functions
It sets the file buffer to read and write. It contains open( ) and close( ) as
filebuf member functions
It supports operations common to the file streams. It serves as a base class
fstreambase for the derived classes ifstream, ofstream and fstream and contains
open( ) and close( ) as member functions
It supports input operations. It contains open( ) with default input mode
ifstream and inherits get( ), getline( ), read( ), seekg( ) and tellg( ) functions from
istream class defined inside iostream.h file.
It supports output operations. It contains open( ) with default output mode
ofstream and inherits put( ), seekp( ), tellp( ) and write( ) functions from ostream
defined inside iostream.h file.
It supports simultaneous input and output operations. It contains open( )
fstream with default input mode and inherits all the functions from istream and
ostream classes through iostream defined inside iostream.h file

 Types of data Files:


 Text file:
o A text file stores information in readable and printable form(ASCII characters).
o Each line of text is terminated by a special character, known as End of Line (EOL) or
delimiter.
 Binary file:
o A binary file contains information in the non-readable form i.e. in the same format in
which it is held in memory.
o In binary files, no delimiters are used for a line and no translations occur here.

 Opening and Closing of Files:


 A file must first be opened before data can be read from it or written to it. while opening a
file, we need the stream like input, output and input_output.
o To create an input stream you must declare the stream to be of class ifstream.
o To create an output stream you must declare the stream to be of class ofstream.
o Streams that will be performing both input and output operations must be declared as
class fstream.

Computer Science 2 Class 12/PU-II


Kensri School and College, Bengaluru
 In C++ there are two ways to open a file with the file stream object.
o Opening file using constructor.
o Opening file using open ( ) member function.
 The first method is preferred when a single file is used with a stream. However for
managing multiple files with the same stream, the second method is preferred.

 Opening file using constructor:


o In order to access a file, it has to be opened either in read, write or append mode.
o In all the three file stream classes, a file can be opened by passing a filename as the first
parameter in the constructor itself.
o The syntax for opening a file using constructor is
streamclass_name file_objectname (“filename”)

o The syntax of opening a file for output purpose only using an object ofstream class and
the constructor is as follows:
ofstream ofstream_object(“file name”);

 ofstream _object is an object of type ofstream and “file name” is any valid identifier
of a file to be opened for output purpose only.
 fout is declared to be an object of ofstream type and it is made to represent the file
results.dat and text.dat opened for output purpose only.
Example: ofstream fout (“results.dat”);
ofstream output_file(“secret”,ios::out)

o The syntax of opening a file for input purpose only using an object ifstream class and the
constructor is as follows:
ifstream ifstream_object(“file name”);

 ifstream _object is an object of type ifstream and “file name” is any valid identifier
name of a file to opened for input purpose only.
 fin is declared to be an object of ifstream type and it is made to represent the file
results.dat and text.dat opened for input purpose only.
Example: ifstream fin (“results.dat”);
ifstream input_file(“datafile”,ios::in)

 Opening files using open( ):


o open( ) can be used to open multiple files that use the same stream object.
o The syntax for opening a file using open ( ) member function is as follows:
file_stream_class stream_object;
stream_object.open (“file_name”);

o The syntax of opening a file for output purpose only using an object ofstream class and
open( ) member function is as follows:
oftream_object.open(“file name”);

 ofstream-object is an object of type ofstream


 filename is any valid name of a file to be opened for output purpose only
Example: ofstream outfile;
outfile.open (“data”);
outfile.open (“text.dat”);

Computer Science 3 Class 12/PU-II


Kensri School and College, Bengaluru
o The syntax of opening a file for input purpose only using an object ifstream class and
open( ) member function is as follows:
iftream_object.open(“file name”);

 ifstream-object is an object of type ifstream.


 file name is any valid name of a file to be opened for input purpose only.
Example: ifstream ifile;
ifile.open (“data”);
ifile.open(“text.dat”);

o To open a file for both input and output, we declare objects of fstream class. We know
that the class fstream is derived from both ifstream and ofstream.
o The syntax for opening a file an object of type fstream class and the constructor is as
follows:
fstream fstream-object(“file name’, mode);

o The syntax for opening a file an object of type fstream class and the open( ) member
function is as follows:
fstream-object.open(“file name’, mode);

 File Modes:
 While using constructors or open( ), the files were created or opened in the default mode.
 There was only one argument passed, i.e. the filename.
 C++ provides a mechanism of opening a file in different modes in which case the second
parameter must be explicitly passed.
 Syntax: stream_object.open(“filename”, mode);
 Example: fout.open(“data”, ios::app) // This opens the file data in the append mode.
 The lists of file modes are:
Mode Method Meaning Stream Type
ios::app Append to end of the file at opening time ofstream
ios::in Open file for reading, ie. input mode. ifstream
ios::out Open file for writing, ie. output mode. ofstream
ios::ate Open file for updating and move the file pointer to the end of file ifstream
ios::trunc On opening, delete the contents of file ofstream
ios::nocreate Turn down opening if the file does not exists ofstream
ios::noreplace Turn down opening if the file already exists ofstream
ios::binary Opening a binary file ifstream
Example: fstreamfout (“text”, ios::out); // open text in output mode
fstream fin(“text”, ios::in); // open text in input mode
fout.open(“data”, ios::app) // This opens the file data in the append mode
fout.open(“data”, ios::app | ios::nocreate) // This opens the file in the append mode
but fails to open if it does not exist.

 Closing File:
 opening a file establishes the linkage between a stream object and an operating system file.
After the intended operations are done with the file, the file should be safely saved on the
secondary storage for later retrieval.
 The member function close( ) on its execution removes the linkage between the file and the
stream object.
 Syntax: stream_object.close( );
 Example: ofstream.close( );
ifstream.close( );
fout.close();

Computer Science 4 Class 12/PU-II


Kensri School and College, Bengaluru

 Input and output operation in text file:


 The data in text files are organized into lines with new line character as terminator.
 Text file need following types of character input and output operations:
 put( ) function
 get( ) function

 put ( ):
o The put( ) member function belongs to the class ofstream and writes single character to the
associated stream.
o Syntax: ofstream_object.put(ch); // where ch is the character variable.
o Example: char ch=’A’;
ofstream fout(“text.txt”);
fout.put (ch);
o fout is the object of ofstream. Text is the name of the file. Value at ch is written to text.

 get( ):
o The get( ) member function belong to the class ifstream and reads a single character from
the associated stream.
o Syntax: ifstream_object.get (ch); // where ch is the character variable.
o Example: char ch; ifstream fin(“text.txt”);
fin.get (ch);
o fin is the object of ifstream. Text is the name of the file. Reads a character into the variable
ch.

 getline( ):
o It is used to read a whole line of text. It belongs to the class ifstream.
o Syntax: fin.getline(buffer, SIZE)
o It reads SIZE characters from the file represented by the object fin or till the new line
character is encountered, whichever comes first into the buffer.
o Example: char book[SIZE];
ifstream fin;
fin.getline (book, SIZE);

 Input and output operation in binary files:


 Binary files are very much use when we have to deal with database consisting of records.
 The binary format is more accurate for storing the numbers as they are stored in the exact
internal representation.
 There is no conversion while saving the data and hence it is faster.
 Functions used to handle data in binary form are:
o write ( ) member function.
o read ( ) member function.

 write ( ):
o The write ( ) member function belongs to the class ofstream and which is used to write
binary data to a file.
o Syntax: ofstream_object.write((char *) & variable, sizeof(variable));
o These functions take 2 arguments. The first is the address of the variable and second the
size of the variable in bytes. The address of the variable must be type casted to pointer to
character.
o Example: student s;
ofstream fout(“std.dat”, ios::binary);
fout.write((char *) &s, sizeof(s));

Computer Science 5 Class 12/PU-II


Kensri School and College, Bengaluru
 read ( ):
o The read ( ) member function belongs to the class ifstream and which is used to read
binary data from a file.
o Syntax: ifstream_object.read((char *) & variable, sizeof(variable));
o These functions take 2 arguments. The first is the address of the variable and second the
size of the variable in bytes. The address of the variable must be type casted to pointer to
character.
o Example: student s;
ifstream fin(“std.dat”, ios::binary);
fin.read((char *) &s, sizeof(s));

 Detecting End of file:


 Detecting end of file is necessary for preventing any further attempt to read data from the file.
 eof( ) is a member function of ios class.
 It returns a non-zero (true) value if the end of file condition is encountered while reading;
otherwise returns a zero (false).
 Example: ifstream fin;
if(fin.eof( ))
{
statements;
}
 This is used to execute set statements on reaching the end of the file by the object fin.

 File pointers and their manipulation:


 In C++, the file I/O operations are associated with the two file pointers:
o Input pointer (get pointer)
o Output pointer (put pointer)
 We use these pointers to move through files while reading or writing.
 Each time an input or output operation takes place, appropriate pointer is automatically
advanced.
o ifstream, like istream, has a pointer known as get pointer that points to the element to be
read in the next input operation.
o ofstream, like ostream, has a pointer known as put pointer that points to the location
where the next element has to be written.
 There are three modes under which we can open a file:
o Read only mode
o Write only mode
o Append mode.

Computer Science 6 Class 12/PU-II


Kensri School and College, Bengaluru
 When we open a file in read only mode, the input pointer is automatically set at the beginning
so that we read the file from the beginning.
 When we open a file in write only mode, the existing contents are deleted and output pointer
is set at the beginning
 If we want to open an existing file to add more data, the file is opened in append mode. This
moves the file pointer to the end of the file.

 Functions for manipulation of file pointers:


 To move file pointers to any desired position inside a file, file stream classes support the
following functions.
o seekg() - Moves get file pointer to a specific location
o seekp() - Moves put file pointer to a specific location
o tellg() - Returns the current position of the get pointer
o tellp() - Returns the current position of the put pointer
 The seekp() and tellp() are member functions of ofstream
 The seekg() and tellg() are member functions of ifstream.
 All four functions are available in the class fstream.

 seekg( ):
 Move the get pointer to a specified location from the beginning of a file.
 There are two types:
o seekg(long);
o seekg(offset, seekdir);
 The seekg(long) moves the get pointer to a specified location from the beginning of a file.
 Example: inf.seekg(20);
 The seekg(offset, seekdir) has two arguments: offset and seekdir.
 The offset indicates the number of bytes the get pointer is to be moved from seekdir position.
 seekdir takes one of the following three seek direction constants.

 Syntax: stream_objectname.seekg(offset, origin_value);


 Example: Some of the pointer offset calls and their actions are shown in the following table

 seekp ( ):
 Move the put pointer to a specified location from the beginning of a file.
 There are two types:
 seekp(long);
 seekp(offset, seekdir);

Computer Science 7 Class 12/PU-II


Kensri School and College, Bengaluru
 The seekp(long) moves the put pointer to a specified location from the beginning of a file.
 Example: inf.seekp(20);
 The seekp(offset, seekdir) has two arguments: offset and seekdir.
 The offset indicates the number of bytes the put pointer is to be moved from seekdir position.
 Syntax: stream_objectname.seekp(offset, origin_value);

 tellg ( ) and tellp( ):


 tellg( ) returns the current position of the get pointer.
o Syntax: position = ifstream_object.tellg( );
o Example: int position position= fin.tellg();
 tellp( ) returns the current position of the put pointer.
o Syntax: position = ifstream_object.tellp( );
o Example: int position position= fin.tellp();

 Error Handling During File I/O


 Sometimes during file operations, errors may also creep in.
 For example:
o A file being opened for reading might not exist. Or
o A file name used for a new file may already exist. Or
o An attempt could be made to read past the end-of-file. Or
o such as invalid operation may be performed.
o There might not be enough space in the disk for storing data.
 To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-
state' members from the ios class that store the information on the status of a file that is being
currently used. The current state of the I/O system is held in an integer,

Name Meaning
eofbit 1 when end-of-file is encountered, 0 otherwise.
failbit 1 when a non-fatal I/O error has occurred, 0 otherwise
badbit 1 when a fatal I/O error has occurred, 0 otherwise
goodbit 0 value

 Error Handling Functions


There are several error handling functions supported by class ios that help you read and
process the status recorded in a file stream.

Function Meaning
int bad() Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has
occurred. However, if it is zero (false value), it may be possible to recover from any other
error reported and continue operations.
int eof() Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns
zero (false value).
int fail() Returns non-zero (true) when an input or output operation has failed.
int Returns non-zero (true) if no error has occurred. This means, all the above functions are

Computer Science 8 Class 12/PU-II


Kensri School and College, Bengaluru
good() false. For example, if fin.good() is true, everything is okay with the stream named as fin
and we can proceed to perform I/O operations. When it returns zero, no further operations
can be carried out.
clear() Resets the error state so that further operations can be attempted.
(
 eof() returns true if eofbit is set;
 bad() returns true if badbit is set.
 fail() function returns true if failbit is set;
 good() returns true there are no errors. Otherwise, they return false.)

 This program demonstrates the concept of handling the errors during file operations in a
program
#include<iostream.h>
#include<fstream.h>
#include<process.h>
#include<conio.h>
void main()
{
clrscr();
char fname[20];
cout<<"Enter file name: ";
cin.getline(fname, 20);
ifstream fin(fname, ios::in);
if(!fin)
{
cout<<"Error in opening the file\n";
cout<<"Press a key to exit...\n";
getch();
exit(1);
}
int val1, val2;
int res=0;
char op;
fin>>val1>>val2>>op;
switch(op)
{
case '+':
res = val1 + val2;
cout<<"\n"<<val1<<" + "<<val2<<" = "<<res;
break;
case '-':
res = val1 - val2;
cout<<"\n"<<val1<<" - "<<val2<<" = "<<res;
break;
case '*':
res = val1 * val2;
cout<<"\n"<<val1<<" * "<<val2<<" = "<<res;
break;
case '/':
if(val2==0)
{
cout<<"\nDivide by Zero Error..!!\n";
cout<<"\nPress any key to exit...\n";

Computer Science 9 Class 12/PU-II


Kensri School and College, Bengaluru
getch();
exit(2);
}
res = val1 / val2;
cout<<"\n"<<val1<<" / "<<val2<<" = "<<res;
break;
}
fin.close();
cout<<"\n\nPress any key to exit...\n";
getch();
}

SAMPLE PROGRAMS :
 Program to illustrate file handling.
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream ofile;
ofile.open ("text.txt");
ofile << "Hello" << endl;
cout << "Data written to file" << endl;
ofile.close();
return 0;
}
_________________________________________________________________________________
Output:
The program prints "Hello" in the file text.txt

 Program to Create a file.


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{
fstream file; //object of fstream class
file.open("text.txt",ios::out); //opening file "sample.txt" in out(write) mode
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
cout<<"File created successfully.";
file.close(); //closing the file
getch();
}
_________________________________________________________________________________
Output:
File created successfully.";

 The program takes input from text.txt file and then prints on the terminal.

#include<iostream.h>

Computer Science 10 Class 12/PU-II


Kensri School and College, Bengaluru
#include<fstream.h>
int main()
{
char data[100];
ifstream ifile;
ifile.open ("text.txt"); //create a text file before executing.
while ( !ifile.eof() )
{
ifile.getline (data, 100);
cout << data << endl;
}
ifile.close();
return 0;
}
_________________________________________________________________________________
Output:
(The program takes input from text.txt file and then prints on the terminal.)
Hello
Data written to file.

 C++ program to read a text file.


 Open file in read/input mode using std::in
 Check file exists or not, if it does not exist terminate the program
 If file exist, run a loop until EOF (end of file) not found
 Read a single character using cin in a temporary variable
 And print it on the output screen
 Close the file

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
int main()
{
char ch;
clrscr();
const char *fileName="text.txt";
ifstream file; //declare object
file.open(fileName,ios::in); //open file
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return -1; //return from main
}
//read and print file content
while (!file.eof())
{
file >> ch; //reading from file
cout << ch; //printing
}
file.close(); //close the file
getch();

Computer Science 11 Class 12/PU-II


Kensri School and College, Bengaluru
}
________________________________________________________________________________
Output:
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.

 C++ program to write and read text in/from file


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{
fstream file; //object of fstream class
file.open("sample.txt",ios::out); //opening file in out(write) mode
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
cout<<"File created successfully."<<endl;
file<<"ABCD."; //write text into file
file.close(); //closing the file
//again open file in read mode
file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
file.close(); //close file
getch();
}
________________________________________________________________________________
Output:
File created successfully.
File content: ABCD.

 C++ program to write and read values using variables in/from file
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main()
{

Computer Science 12 Class 12/PU-II


Kensri School and College, Bengaluru
char name[30];
int age;
clrscr();
fstream file;
file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
cout<<"Enter your name: "; //read values from kb
cin.getline(name,30);
cout<<"Enter age: ";
cin>>age;
file<<name<<" "<<age<<endl; //write into file
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;
//re open file in input mode and read data
file.open("aaa.txt",ios::in);
if(!file)
{
cout<<"Error in opening file..";
return 0;
}
file>>name;
file>>age;
cout<<"Name: "<<name<<",Age:"<<age<<endl;
getch();
}
________________________________________________________________________________
Output:
File created successfully.
Enter your name: Ravi
Enter age: 28

File saved and closed succesfully.


Name: Ravi,Age:28

 C++ program to write and read object using read and write function.
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
class student //class student to read and write student details
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}

Computer Science 13 Class 12/PU-II


Kensri School and College, Bengaluru
void showData(void)
{ cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};
int main()
{
student s;
ofstream file;
file.open("aaa.txt",ios::out); //open file in write mode
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file
file.close(); //close the file
cout<<"\nFile saved and closed succesfully."<<endl;
//re open file in input mode and read data
ifstream file1;
file1.open("aaa.txt",ios::in); //again open file in read mode
if(!file1)
{ cout<<"Error in opening file..";
return 0;
}
file1.read((char*)&s,sizeof(s)); //read data from file
s.showData(); //display data on monitor
file1.close(); //close the file
getch();
}
________________________________________________________________________________
Output:
File created successfully.
Enter your name: Ravi
Enter age: 28
File saved and closed successfully.
Name: Ravi,Age:28

 C++ program to write and read time in/from binary file using fstream
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h> //for setfill() and setw()
#define FILE_NAME "time.dat"
void writeTime(int h, int m, int s) //function to write time into the file
{
char str[10];
fstream file;
file.open(FILE_NAME, ios::out|ios::binary);
if(!file)
{
cout<<"Error in creating file!!!"<<endl; //make string to write
return;

Computer Science 14 Class 12/PU-II


Kensri School and College, Bengaluru
}
sprintf(str,"%02d:%02d:%02d",h,m,s);
file.write(str,sizeof(str)); //write into file
cout<<"Time "<<str<<" has been written into file."<<endl;
file.close(); //close the file
}
void readTime(int *h,int *m, int *s) //function to read time from the file
{
char str[10];
int inH,inM,inS;
fstream finC;
finC.open(FILE_NAME,ios::in|ios::binary);
if(!finC)
{
cout<<"Error in file opening..."<<endl;
return;
}
if(finC.read((char*)str,sizeof(str)))
{
//extract time values from the file
sscanf(str,"%02d:%02d:%02d",&inH,&inM,&inS);
//assign time into variables, which are passing in function
*h=inH;
*m=inM;
*s=inS;
}
finC.close();
}
int main()
{
int m,h,s;
cout<<"Enter time:\n";
cout<<"Enter hour: "; cin>>h;
cout<<"Enter minute: "; cin>>m;
cout<<"Enter second: "; cin>>s;
writeTime(h,m,s); //write time into file
h=m=s=0; //now, reset the variables
readTime(&h,&m,&s); //read time from the file
//print the time
cout<<"The time is "<<setw(2)<<setfill('0')<<h<<":"<<setw(2)
cout<<setfill('0')<<m<<":" <<setw(2)<<setfill('0')<<s<<endl;
return 0;
}
________________________________________________________________________________
Output:
Enter time:
Enter hour: 10
Enter minute: 15
Enter second: 5
Time 10:15:05 has been written into file.
The time is 10:15:05

 WAP to create a single file and then display its contents.

Computer Science 15 Class 12/PU-II


Kensri School and College, Bengaluru
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
system("cls");
ofstream fout("student", ios::out);
char name[30], ch;
float marks =0.0;
for(int i=0;i<5;i++) //Loop to get 5 records
{
cout<<"Student "<<(i+1)<<":\tName: ";
cin.get(name,30);
cout<<"\t\tMarks: ";
cin>>marks;
cin.get(ch); //to empty input buffer write to the file
fout<<name<<"\n"<<marks<<"\n";
}
fout.close(); //disconnect student file from fout
ifstream fin("student", ios::in); //connect student file to input stream fin
fin.seekg(0); //To bring file pointer at the file beginning
cout<<"\n";
for(i=0;i<5;i++) //Display records
{
fin.get(name,30); //read name from file student
fin.get(ch);
fin>>marks; //read marks from file student
fin.get(ch);
cout<<"Student Name: "<<name;
cout<<"\tMarks: "<<marks<<"\n";
}
fin.close(); //disconnect student file from fin stream
getch();
}
________________________________________________________________________________
Output:
Student 1: Name : Ravi
Marks : 80
Student 2: Name : Praveen
Marks : 90
Student 3: Name : Sango
Marks : 85
Student 4: Name : Amodh
Marks : 70
Student 5: Name : Ajeya
Marks : 60

Student Name : Ravi Marks : 80


Student Name : Praveen Marks : 90
Student Name : Sango Marks : 85
Student Name : Amodh Marks : 70
Student Name : Ajeya Marks : 60

Computer Science 16 Class 12/PU-II


Kensri School and College, Bengaluru

 Program to display of a file using get() function


#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin;
char ch;
fin.open("demo.txt");
cout<<"\nData in file...";
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}
_________________________________________________________________________________
Output :
Data in file...
Hello friends, my name is kumar.

 Program to display of a file using put() function


#include<fstream.h>
#include<conio.h>
void main()
{
ofstream fout;
char ch;
fout.open("demo.txt");
do
{
cin.get(ch);
fout.put(ch);

}while(ch!=EOF);
fout.close();
cout<<"\nData written successfully...";
}
_________________________________________________________________________________
Output :
Hello friends, my name is kumar.
Data written successfully...

 Program for write() function


#include<fstream.h>
#include<conio.h>
class Student
{
int roll;
char name[25];
float marks;

Computer Science 17 Class 12/PU-II


Kensri School and College, Bengaluru
void getdata()
{
cout<<"\n\nEnter Roll : ";
cin>>roll;
cout<<"\nEnter Name : ";
cin>>name;
cout<<"\nEnter Marks : ";
cin>>marks;
}
public:
void AddRecord()
{
fstream f;
Student Stu;
f.open("Student.dat",ios::app|ios::binary);
Stu.getdata();
f.write( (char *) &Stu, sizeof(Stu) );
f.close();

}
};
void main()
{
Student S;
char ch='n';
do
{
S.AddRecord();
cout<<"\n\nDo you want to add another data (y/n) : ";
ch = getche();

} while(ch=='y' || ch=='Y');
cout<<"\nData written successfully...";
}
_________________________________________________________________________________
Output :

Enter Roll : 1
Enter Name : Ashish
Enter Marks : 78.53

Do you want to add another data (y/n) : y

Enter Roll : 2
Enter Name : Kaushal
Enter Marks : 72.65

Do you want to add another data (y/n) : y

Enter Roll : 3
Enter Name : Vishwas
Enter Marks : 82.65

Do you want to add another data (y/n) : n

Computer Science 18 Class 12/PU-II


Kensri School and College, Bengaluru

Data written successfully...

 Program for read() function


#include<fstream.h>
#include<conio.h>
class Student
{
int roll;
char name[25];
float marks;
void putdata()
{
cout<<"\n\t"<<roll<<"\t"<<name<<"\t"<<marks;
}
public:
void Display()
{
fstream f;
Student Stu;
f.open("Student.dat",ios::in|ios::binary);
cout<<"\n\tRoll\tName\tMarks\n";
while( (f.read((char*)&Stu,sizeof(Stu))) != NULL )
Stu.putdata();
f.close();
}
};
void main()
{
Student S;
S.Display();
}
________________________________________________________________________________
Output :
Roll Name Marks
1 Ashish 78.53
2 Kaushal 72.65
3 Vishwas 82.65

 BASIC OPERATION ON BINARY FILE:


 Searching
 Appending data
 Inserting data in sorted files
 Deleting a record
 Modifying data

 Searching in a file.
We can perform search in a binary file opened in input mode by reading each record then
checking whether it is our desired record or not. For instance, if you want to search for a record for a
student having rollno as 1 in file marks.dat, you can implement this search process in C++ in two
manners :
 with records implemented through structures.
 with records implemented through classes.

Computer Science 19 Class 12/PU-II


Kensri School and College, Bengaluru

 This program demonstrates the searching operation using Structure.


struct student
{
int rollno;
char name[20];
char branch[3];
float marks;
char grade;
}stud1;

ifstream fin("marks.dat", ios::in | ios::binary);


cout<<”Enter rollno to be searh for:”;
cin>>rn;
while(!fin.eof())
{
fin.read((char *)&stud1, sizeof(stud1)); // read record
if(stud1.rollno == rn) // if true, record is found
{
cout<<stud1.name<<”,rollno”<<rn<<” has”<<stud1.marks
<<”% marks and”<<stud1.grade<<”grade. \n”;
found = 'y'; // after processing you may jump from the
break; // loop employed form searching purpose
}
}

if(found == 'n') // record not found


cout<<””Rollno not found in file!\n”;
fin.close();
getch();
}

 Program to demonstrates the searching operation using Classes.


#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
class student
{
int rollno;
char name[20], branch[3], grade;
float marks;
public:
void getdata()
{
cout<<"Rollno: "; cin>>rollno;
cout<<"Name: "; cin>>name;
cout<<"Branch: "; cin>>branch;
cout<<"Marks: "; cin>>marks;
if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }

Computer Science 20 Class 12/PU-II


Kensri School and College, Bengaluru
else if(marks>=50)
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}
void putdata()
{
cout<<"Rollno: "<<rollno<<"\tName: "<<name<<"\n";
cout<<"Marks: "<<marks<<"\tGrade: "<<grade<<"\n";
}
int getrno()
{ return rollno; }
}stud1;
void main()
{
clrscr();
fstream fio("marks.dat", ios::in | ios::out);
char ans='y';
while(ans=='y' || ans=='Y')
{
stud1.getdata();
fio.write((char *)&stud1, sizeof(stud1));
cout<<"Record added to the file\n";
cout<<"\nWant to enter more ? (y/n)..";
cin>>ans;
}
clrscr();
int rno;
long pos;
char found='f';
cout<<"Enter rollno of student to be search for: ";
cin>>rno;
fio.seekg(0);
while(!fio.eof())
{
pos=fio.tellg();
fio.read((char *)&stud1, sizeof(stud1));
if(stud1.getrno() == rno)
{
stud1.putdata();
fio.seekg(pos);
found='t';
break;
}
}
if(found=='f')
{
cout<<"\nRecord not found in the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(2);
}

Computer Science 21 Class 12/PU-II


Kensri School and College, Bengaluru
fio.close();
getch();
}

 Appending Data
To append data in a file, the file is opened with the following two specifications :
 file is opened in output mode
 file is opened in ios::app mode
Once the file gets opened in ios::app mode, the previous records/information is retained and new
data gets appended to the file.
 Program to demonstrates append data in a file.
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
class student
{
int rollno;
char name[20];
char branch[3];
float marks;
char grade;
public:
void getdata()
{
cout<<"Rollno: "; cin>>rollno;
cout<<"Name: "; cin>>name;
cout<<"Branch: "; cin>>branch;
cout<<"Marks: "; cin>>marks;
if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }
else if(marks>=50)
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}

void putdata()
{
cout<<name<<", rollno "<<rollno<<" has ";
cout<<marks<<"% marks and "<<grade<<" grade."<<"\n";
}

int getrno()
{ return rollno; }
}stud1;

void main()
{

Computer Science 22 Class 12/PU-II


Kensri School and College, Bengaluru
clrscr();
ofstream fout("marks.dat", ios::app);
char ans='y';
while(ans=='y' || ans=='Y')
{
stud1.getdata();
fout.write((char *)&stud1, sizeof(stud1));
cout<<"Data appended in the file successfully..!!\n";
cout<<"\nWant to enter more ? (y/n)..";
cin>>ans;
}
fout.close();
cout<<"\nPress any key to exit...\n";
getch();
}

 Inserting Data in Sorted File


To insert data in a sorted file, firstly, its appropriated position is determined and then records
in the file prior to this determined position are copied to temporary file, followed by the new record
to be inserted and then the rest of the records from the file are also copied.

For example, records in marks.dat are sorted in ascending order on the basis of rollno. Assuming
that there are about 10 records in the file marks.dat. Now a new record with rollno 5 is to be
inserted. It will be accomplished as follows :
 Determining the appropriate position. If the rollno of new record say NREC in which rollno 5
is lesser than the rollno of very first record, then the position is 1, where the new record is to
be inserted as it will be inserted in the beginning of the file to maintain the sorted order.
If the rollno of new record (5 here) satisfies following condition for two consecutive records
say (pth and (p + 1)th)
if prev.getrno() <= NREC.getrno() && (NREC.getrno() <= next.getrno())
then the appropriate position will be position of prev + 1 i.e, p + 1.
And if the rollno of the new record is more than the rollno of last record (say nth record) then
the appropriate position will be n+1.
 Copy the records prior to determined position to a temporary file say temp.dat.
 Append the new record in the temporary file temp.dat.
 Now append the rest of the records in temporary file temp.dat.
 Delete the file marks.dat by using the following code.
remove("marks.dat");
 Now, rename the file temp.dat as marks.dat as follows :

rename("temp.dat", "marks.dat");

 Program to demonstrates insert data in a sorted file.


#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
class student
{
int rollno;
char name[20], branch[3], grade;
float marks;

Computer Science 23 Class 12/PU-II


Kensri School and College, Bengaluru
public:
void getdata()
{
cout<<"Rollno: "; cin>>rollno;
cout<<"Name: "; cin>>name;
cout<<"Branch: "; cin>>branch;
cout<<"Marks: "; cin>>marks;
if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }
else if(marks>=50)
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}
void putdata()
{
cout<<"Rollno: "<<rollno<<"\tName: "<<name<<"\n";
cout<<"Marks: "<<marks<<"\tGrade: "<<grade<<"\n";
}
int getrno()
{
return rollno;
}
}stud1, stud;
void main()
{
clrscr();
ifstream fin("marks.dat", ios::in);
ofstream fout("temp.dat", ios::out);
char last='y';
cout<<"Enter details of student whose record is to be inserted\n";
stud1.getdata();
while(!fin.eof())
{
fin.read((char *)&stud, sizeof(stud));
if(stud1.getrno()<=stud.getrno())
{
fout.write((char *)&stud1, sizeof(stud1));
last = 'n';
break;
}
else
{
fout.write((char *)&stud, sizeof(stud));
}
}
if(last == 'y')
{
fout.write((char *)&stud1, sizeof(stud1));
}

Computer Science 24 Class 12/PU-II


Kensri School and College, Bengaluru
else if(!fin.eof())
{
while(!fin.eof())
{
fin.read((char *)&stud, sizeof(stud));
fout.write((char *)&stud, sizeof(stud));
}
}
fin.close();
fout.close();
remove("marks.dat");
rename("temp.dat", "marks.dat");
fin.open("marks.dat", ios::in);
cout<<"File now contains:\n";
while(!fin.eof())
{
fin.read((char *)&stud, sizeof(stud));
if(fin.eof())
{ break; }
stud.putdata();
}
fin.close();
getch();
}

 Deleting a Record From A File


 Firstly, determine the position of the record to be deleted, by performing a search in the file.
 Keep copying the records other than the record to be delete in a temporary file say temp.dat.
 Do not copy the record to be deleted to temporary file, temp.dat.
 Copy rest of the records to temp.dat.
 Delete original file say marks.dat as :
remove("marks.dat");
 Rename temp.dat as marks.dat as :
rename("temp.dat", "marks.dat");

#include"fstream.h"
#include"conio.h"
#include"stdio.h" //for rename and remove
class stu
{
int rollno;
char name[15],Class[4];
float marks;
char grade;
public:
void getdata();
void putdata();
int getrno() //access roll no
{
return rollno;
}
}s1,stud;

Computer Science 25 Class 12/PU-II


Kensri School and College, Bengaluru

void stu::getdata()
{
cout<<"enter roll no:";
cin>>rollno;
cout<<"enter name :";
cin>>name;
cout<<"enter class :";
cin>>Class;
cout<<"enter marks :";
cin>>marks;
if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }
else if(marks>=50)
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}

void stu::putdata()
{
cout<<"roll no:"<<rollno<<"\t Name:"<<name<<"\n Marks:"<<marks
cout<<"\t grade :"<<grade;
}

void main()
{
clrscr();
ifstream fio("marks.dat",ios::in); //marks must exist on disk
ofstream file("temp.dat",ios::out|ios::app);
int rno;
char found='f',confirm='n';
cout<<"Enter rollno of student whose record is to be deleted \n";
cin>>rno;
while(!fio.eof())
{
fio.read((char*)&s1,sizeof(s1));
if(s1.getrno()==rno)
{
s1.putdata();
found='t';
cout<<"are you sure want to delete this record(y/n)";
cin>>confirm;
if(confirm=='n') // if confirm is y then record is not written
file.write((char*)&s1,sizeof(s1));
}
else
file.write((char*)&s1,sizeof(s1));
}
if(found=='f')

Computer Science 26 Class 12/PU-II


Kensri School and College, Bengaluru
cout<<"Record not found!!\n";
fio.close();
file.close();
remove("marks.dat");
rename("temp.dat","marks.dat");
fio.open("marks.dat",ios::in);
cout<<"Now file contains \n";
while(!fio.eof())
{ fio.read((char*)&stud,sizeof(stud));
if(fio.eof())break;
stud.putdata();
}
fio.close();
getch();
}

 Modifying Data in Given File


To modify a record, the file is opened in I/O mode and an important step is performed that gives
the beginning address of record being modified. After the record is modified in memory, the file
pointer is once again placed at the beginning position of this record and then record is rewritten.

#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream.h>
class student
{
int rollno;
char name[20];
char branch[3];
float marks;
char grade;

public:
void getdata()
{
cout<<"Rollno: ";
cin>>rollno;
cout<<"Name: ";
cin>>name;
cout<<"Branch: ";
cin>>branch;
cout<<"Marks: ";
cin>>marks;

if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }
else if(marks>=50)

Computer Science 27 Class 12/PU-II


Kensri School and College, Bengaluru
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}

void putdata()
{
cout<<"Rollno: "<<rollno<<"\tName: "<<name<<"\n";
cout<<"Marks: "<<marks<<"\tGrade: "<<grade<<"\n";
}

int getrno()
{
return rollno;
}
void modify();
}stud1, stud;

void student::modify()
{
cout<<"Rollno: "<<rollno<<"\tName: "<<name<<"\n";
cout<<"Marks: "<<marks<<"\tGrade: "<<grade<<"\n";
cout<<"Enter new details"<<endl;
char nm[20]=" ",cl[4]=" ";
float mks;
cout<<"New Name : (Enter '.' to retain old one)";
cin>>nm;
cout<<"New Class : (Press '.' to retain old one)";
cin>>cl;
cout<<"New Marks : (Press-1 to retain old one)";
cin>>mks;
if(strcmp(nm,".")!=0)
strcpy(name,nm);
if(strcmp(cl,".")!=0)
strcpy(branch,cl);
if(mks!=-1)
{ marks=mks;
if(marks>=75)
{ grade = 'A'; }
else if(marks>=60)
{ grade = 'B'; }
else if(marks>=50)
{ grade = 'C'; }
else if(marks>=40)
{ grade = 'D'; }
else
{ grade = 'F'; }
}
}

int main()
{

Computer Science 28 Class 12/PU-II


Kensri School and College, Bengaluru
fstream fio("marks.dat", ios::in|ios::out|ios::binary);
/* Read rollno whose data is to be modified */
int rno;long pos;char found='f';
cout<<"Enter rollno of student whose recoed is to be modified\n";
cin>>rno;
while(!fio.eof())
{
pos = fio.tellg(); // determine the beginning position of record
fio.read((char *) & stud1, sizeof(stud1));
if(stud1.getrno() == rno) // this is the record to be modified
{
stud1.modify(); // get the new data
fio.seekg(pos); // place file pointer at the beginning record position
fio.write((char *) & stud1, sizeof(stud1)); // now write the modified record
found='t';
break;
}
}
if(found=='f')
cout<<"Record not found\n";
fio.seekg(0);
cout<<"Now the file contains\n";
while(!fio.eof())
{
fio.read((char*)&stud1,sizeof(stud1));
stud.putdata();
}
fio.close();
getch();

 Merge Two Files


So the following C++ program ask to the user to enter three file names. First file name and
second file name (say file1.txt and file2.txt), then Third file name that is used to store the content of
the two file (say filet.txt).

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
ifstream ifiles1, ifiles2;
ofstream ifilet;
char ch, fname1[20], fname2[20], fname3[30];
cout<<"Enter first file name (with extension like file1.txt) : ";
gets(fname1);
cout<<"Enter second file name (with extension like file2.txt) : ";
gets(fname2);
cout<<"Enter name of file (with extension like file3.txt) which will store

Computer Science 29 Class 12/PU-II


Kensri School and College, Bengaluru
the contents of the two files (fname1 and fname1) : ";
gets(fname3);
ifiles1.open(fname1);
ifiles2.open(fname2);
if(ifiles1==NULL || ifiles2==NULL)
{
perror("Error Message ");
cout<<"Press any key to exit...\n";
getch();
exit(EXIT_FAILURE);
}
ifilet.open(fname3);
if(!ifilet)
{
perror("Error Message ");
cout<<"Press any key to exit...\n";
getch();
exit(EXIT_FAILURE);
}
while(ifiles1.eof()==0)
{
ifiles1>>ch;
ifilet<<ch;
}
while(ifiles2.eof()==0)
{
ifiles2>>ch;
ifilet<<ch;
}
cout<<"The two files were merged into "<<fname3<<" file successfully..!!";
ifiles1.close();
ifiles2.close();
ifilet.close();
getch();
}

Computer Science 30 Class 12/PU-II

S-ar putea să vă placă și