+ All Categories
Home > Documents > Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7 Data

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7 Data

Date post: 03-Feb-2022
Category:
Upload: others
View: 6 times
Download: 0 times
Share this document with a friend
59
Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7 Data File Handling Introduction The fstream.h Header file Data Files Opening and Closing File Steps to process a File in your Program Changing the behavior of Stream Sequential I/O With Files Detecting EOF File Pointers and Random Access Basic Operation on Files Error Handling During I/O
Transcript

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Data File Handling� Introduction� The fstream.h Header file� Data Files� Opening and Closing File� Steps to process a File in your Program� Changing the behavior of Stream� Sequential I/O With Files� Detecting EOF� File Pointers and Random Access� Basic Operation on Files� Error Handling During I/O

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Introduction of File� Most Computer Programs work with files.

� Word Processor creates documents file, Databasecreates files of Information, Compilers readsource file and generates executable files. So,

� File itself is a bunch of bytes stored on somestorage device like tape, or Magnetic disk etc.

� In C++, File Input/Output facility areimplemented through a component header file ofC++ standard library. This header file is fstream.h

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

fstream.h Header File� The C++ input/output operation are very much

similar to the console input and output operation.The file operations also make use of streams asan interface between the programs and the files.

� What is stream?� A streamis a sequence of Bytes.� A streamis a general name given to a flowof

data . Different streams are used to representdifferent kind of data flow.

� Each streams is associated with a particular class.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Continue…� Each streamis associated with particular class,

which contains member function and definitionsfor dealing with that particular kind of data flow.

� The istreamclass represent input disk file.� The streams that supplies data to the programis

known as input stream. It read the data fromthefile and hands it over to the program.

� The streams that received data fromprogramisknown as output stream.

� It writes the received data to the file .

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Text File� A text file stores information in ASCII characters.

In text files, each line of text is terminated, with special characters known as EOL (End of Line) characters.

� In text files some internal translations take place when this EOL characters is read or written.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Binary Files� A Binary file just a file that contains information

in the same way as it store in memory.

� In binary file, there is no delimiters for a line.

� In binary file, no translation occurs.

� Binary files are faster and easier for a programtoread and write than a text file.

� Binary files are best way to store information

� In C++, the default file systemis “Text” file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Opening the Files� In C++, for open a file, you must first obtains a stream.

There are three types of Stream; Input, Output and Input-Output.

� To create an Input stream, declare the streamto be ofclass istream.

� To create an Output stream, declare the streamto be ofclassostream.

� Streamthat will performboth input and output operationmust be declared asfstream.

� Opening a file can be achieved in two ways.� (1) Using theconstructor function of the streamclass.� (2) Using the functionopen()

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

When we open a file with Constructor

� This method is preferred, when a single file isused with a stream.

When we open a file by open() method

� This method is preferred, when we want tomanage multiple files with same stream.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Opening file using Constructor� To open a file, Data file as an input file ( it means we

will read fromit, but can not modifying it. And no otheroperation like writing and modifying is possible).

� We shall create a file streamobject of input type.ifstreamtype.

� Syntax :� ifstreaminputfile(“Datafile”);� Here inputfile is the object of ifstreamclass and Datafile

is the file name to open in input mode.� After creating the object, datafile is open and attach with

object inputfile.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

How to read data from file� To read the data fromthis file, object of inputfile

is used and by using getfromoperator “>>”

� Syntax…

� char ch;

� inputfile >>ch;

� float amt;

� inputfile >>amt;

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

How to write into the file� Similarly, when we want to write onto the file,

we must open the file in output mode. This isaccomplished by.

� Creating ofstreamobject to manage the outputstream.

� Associating tat object with a particular file

� Syntax..

� ofstreamoutputfile(“datafile”);

� Here outputfile is the object and datafile is file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Extra Notation about file object� The connection with a file are closed

automatically, when the input and output streamobject expire.

� Also you can close connection with a fileexplicitly by using close() method.

� inputfile.close();

� outputfile.close();

� Closing such connection does not eliminate thestream. It just disconnect it fromfile.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Opening a file using open() function� The are many situations requiring a programto open

more than one file. So we need create a separate streamfor each of the file.

� First of all, declares the streamobject without initializingit, then use the second statement and associated a filename.

� Syntax…..� ifstreaminfileobject;� Infileobject.open(“filename.dat”);� To close a file. We can use� infileobject.close();

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Concept of file mode� The filemode describe howa file is to be used. To

read fromit, to write to it, to append it and so on.

� When you associate a streamwith file, either byconstructor or by the open() function, the secondargument is the mode of the file, in which it open.

� Syntax..

� Stream_object.open (“FileName”,Filemode);

� The second argument of open method is of inttype and you can choose one of the mode of file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7S. No

Constant Meaning Stream Type

1 ios::in It opens file for reading, in input mode ifstream

2 ios::out It opens file for writing, in output mode. This also opens the file inios::trunk mode by default. This means an existing file is truncated whenopened. It means the previous contents are discarded.

ofstream

3 ios::ate This seeks to end-of-file upon opening the file, I/O operation can still occuranywhere within the file.

IfstreamOfstream

4 ios::app This causes all output to that file to be appended to the end. This value canbe used only with files capable of output

ofstream

5 ios::trunk This value causes the contents of a pre-existing file by the same name to bedestroyed and truncated the file to zero length.

ofstream

6 ios::noncreate

This cause the open() function to fail if the file does not already exist. Itwill not create a new file with that name.

ofstream

7 ios::noreplace

This causes open() function to fail if the file already exist. This is usedwhen you want to create a new file and at the same time.

ofstream

8 ios::binary This causes a file to be opened in binary mode. By default, files are openedin text mode. When a file opened in text mode, various characterstranslations take place. Such as carriage return to new line. However nosuch character translation occurs in files opened in binarymode.

ofstreamifstream

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Extra Notations about file mode� The ifstreamand ofstreamprovide default mode of the

file is ios::in(input mode)� The fstreamclass does not provide the default mode. It

specify explicitly.� You can combine more than one file mode using bitwise

| (OR) operator.� Ex…� ofstreamfout;� fout.open (“Master”,ios::app | ios::nocreate);� To open a binary file add ios::binary with file mode.� fout.open (“Master”, ios::nocreate | ios::binary);

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Steps to process a file in your Program� Determine the type of link required.

� Declare a stream for the desired type of link.

� Attach the desired file to the stream.

� Now process as required.

� Close the file-link with stream.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Determine the type of link required.� This step is required the type of link, if the data is

to be brought in froma file to memory, then thelink can be said to be File-to-Memory.

� Similarly fif the data is sent frommemory to filethen the link can be said as Memory-to-file.

� If both side need data transfer then two-way linkis created.

� File-to-Memory Input type� Memory-to-file Output type� File-to-Memory & Memory-to-file // I/Otype

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Declaring the stream for type of link� After determining the type of the link, next step is

create a streamfor it. In order to create the filestream, the header file <fstream.h> is included inthe program, and if you have <fstream.h> then noneed to include <iostream.h.> as cin, cout. Theseare also available in <fstream.h>.

� istreamfi; // here streamname is fi;

� ofstreamfo; // here streamname is fo;

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Attach desired file to declare stream� In this step we want to attach a file with the

created streamin second step. This can be done intwo ways

� Using Constructor.

� Using open() method

� ifstreamfin(“sample.dat”); // sample.dat is a file.

� fin.open(“sample.dat”,ios::in) // ios::in file mode

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Process as required.

� Under this step, whatever process is required forthe given problem, is performed for instance.

Close the file link with stream

� This is the final step where we de-link the filewith stream. This is performed through close ()function

� ifstreamfin;

� fin.close();

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

EX

#include<fstream.h>void main(){ofstream filout;filout.open("marks.dat",ios::out);char ans='y';int follno; float marks;while(ans=='y' || ans=='Y'){cout<<endl<<"Enter rollno ";cin>>rollno;

cout<<endl<<"Etner Marks ";cin>>marks;}filout<<rollno<<"\n"<<marks<<"\n";cout<<'\n Do you want to add more record ";cin>>ans;}filout.close();}

After the Executing the program, we can open the file marks.dat in notepad and see the data is reached in the file or not

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

#include<fstream.h>#include<conio.h>void main(){ int i;ofstream fout("Student");char name[25],ch;float marks=0.0;clrscr();for(i=0;i<5;i++){cout<<"Student "<<i+1 <<":\t Name ";cin.get(name,25);cout<<"\t Marks ";cin>>marks; cin.get(ch);fout<<name<<"\n"<<marks<<"\n"; }

Q. Write a C++ program to wite 5 students name in student file and again read it from file

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

fout.close();ifstream fin("Student");fin.seekg(0);cout<<"\n";for(i=0;i<5;i++){fin.get(name,25);fin.get(ch);fin>>marks;fin.get(ch);cout<<"Student Name "<<name;cout<<"\t Marks : "<<marks<< "\n ";}fin.close();getch(); }

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Changing the behavior of Stream� When you open a file, it means when you link a file with

streamusing constructor, the streamis activated in itsdefault mode.

� The default mode in input type streamis ios::in and foroutput type streamis ios::out.

� The default behavior of ifstreamtype streamallow userto read content fromthe file. If the file mode is ios::inonly (fin.open(“abc.dat”,ios::in)) then reading isperformed in text file only.

� If the file mode is ios::in | ios::binary then reading isperformed on binary file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Write a C++ program to append data in already stored file marks.dat

#include<fstream.h>void main(){ofstream fout;fout.open("marks.dat",ios::app);char ans='y';int rollno; float marks;while(ans=='y' || ans=='Y'){cout<<endl<<"Enter Rollno ";cin>>rollno;cout<<endl<<"Etner Marks ";cin>>marks;}

fout<<rollno<<"\n"<<marks<<"\n";cout<<'\n Do you want to add more record ";cin>>ans;}fout.close();}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

get(), getline() and put() function� The function get() and put() are byte oriented.� get() will read byte of data and put() will write byte of

data.� The get() have many forms and used as ..� istream& get(char & ch);� ostream& put(char ch);� The get() function reads a single characters fromthe

associated streamand put the value in ch. It returns thereference to the stream.

� The put write the value of ch to the streamand returnsthe reference to the stream.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Write a program to display the content of file

#include<fstream.h>#include<conio.h>int main(){clrscr();char ch;ifstream fin;fin.open("c:\\ab.txt",ios::in);if(!fin){cout<<"\n Cannot open the file ";return(0);}

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Write a program to create a file using put()

#include<fstream.h>#include<conio.h>int main(){clrscr();ofstream fout;fout.open("c:\\abc.txt",ios::out);if(!fout){cout<<"\n Cannot open the file ";return(0);}

for(int i=65;i<=90;i++){fout.put((char)i);}fout.close();getch();return 0;}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Another forms of get()� Other forms of get() as follows� istream& get(char *buf, int num, char delt)� int get();� The first formread the characters into a character array pointed to

by buf until either numcharacter have been read or the characterspecified by delt has been occur. For Example…

� char line[40];� cin.get(line,40,’$’);� This will read characters into line either 40 characters or $ is

encountered which ever is occur first.� The second formof get() returns the next character fromstream, it

returns EOF if end of file encountered. Ex..� int i; char ch;� ch = i = fin.get();� If ‘A’ is read then value of i will 65 and ch will ‘A’

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

getline() function.� This function read a line into the characters array.

� istream& getline(char *buf, int num, char delm)

� This function virtually identical with get() function

� This function also reads the characters frominputstream and placed it onto the characters array,either number of characters specified or thedelimiter character is encountered.

� cin.getline(a,40,’$’);

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Difference between getline() & get()

� The difference between get(buf,num,delt) andgetline() is that getline() read and remove thedelimeter new-line character fromthe input streamif it is encountered which is not done in get().

void main(){char nm[40],n[40];int i;clrscr();cout<<"Enter First String ";cin.getline(nm,40,'$');cout<<"Enter Second String ";

cin.get(n,40,'%');cout<<endl<<nm<<strlen(nm);cout<<endl<<n<<strlen(n);getch();}

EX

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Difference between getline() & get()

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Programming diff. b/n get and getline#include<fstream.h>#include<conio.h>#include<string.h>void main(){char nm[40],n[40],ch;int i;clrscr();cout<<"Enter First String ";cin.get(nm,40);//cin.get(ch);cout<<"Enter Second String ";cin.getline(n,40);cout<<endl<<nm<<strlen(nm);cout<<endl<<n<<strlen(n);getch();}

Without cin.get(ch) output is

With cin.get(ch) output is

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7Read a text file and create a file that stores the text line by line

along with line nos.

#include<fstream.h>#include<conio.h>int main(){char line[75];int lc=0;ofstream outfile("f11.cpp",ios::app);ifstream infile("f1.cpp",ios::in);clrscr();if (!infile){cout<<"Failed to open input file ";return 0;}

while(!infile.eof()) // while(1){infile.getline(line,75);//if (infile.eof()) break; lc++;outfile<<lc<<":"<<line<<"\n";}infile.close();outfile.close();cout<<"OUTPUT "<<lc<<" Records"<<endl;getch();return 0;}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

The read() and write() function� To manipulate binary data into the file we use

two another function read() and write() as follow

� istream& read( (char *) & buf , int sizeof(buf));

� ostream& write((char *) & buf ,int sizeof(buf));

� The data written to a file using write can only beread accurately using read().

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Read and write a binary file using struct

#include<fstream.h>#include<conio.h>#include<string.h>struct customer{ char name[25]; float bal;};int main(){customer savec;clrscr();strcpy(savec.name,"123546");savec.bal=5412.25;ofstream fout("saving",ios::out|ios::binary);if (!fout){cout<<"File can't be open ";return 0;}

fout.write((char *) & savec, sizeof(customer));fout.close();ifstream fin("saving",ios::in|ios::binary);fin.read((char *) & savec, sizeof(customer));cout<<savec.name;cout<<savec.bal;getch();return 0;}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Read and write a binary file using class#include<fstream.h>#include<conio.h>class student{char name[25];int rollno;public:void readdata();void printdata();};void student :: readdata(){cout<<endl<<"Enter Name ";cin>>name;cout<<endl<<"Enter Rollno ";cin>>rollno;}

void student :: printdata(){cout<<endl<<"Name = "<<name;cout<<endl<<"Rollno = "<<rollno;}void main() {fstream file; student s,t ;file.open("file.txt",ios::out|ios::in|ios::binary);clrscr();s.readdata();file.write((char *) &s, sizeof(s));s.readdata();file.write((char *) &s, sizeof(s));file.seekg(0);file.read((char *) &t, sizeof(t));t.printdata();file.read((char *) &t, sizeof(t));t.printdata();getch(); }

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Detecting EOF � We can detect, when the end of file is reached by

using the member function eof();

� Syntax

� int eof();ifstream fin;fin.open("Master",ios::in);while(!fin.eof()){........}if (fin.eof())cout<<"End of file is reached ";

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

File pointers and Random Access� Every file maintain two pointers called get_pointer

(in input mode file) and put_pointer (in outputmode file) which is tell the current position in thefile where writing and reading take place. Filepointer not a pointer in c++, but it is like a bookmark for the file.

� By these pointers we can maintain a file in randomaccess way. This means we can read fromanywhere and write onto any where in the file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

seekg(), seekp() & tellg() , tellp().� In C++ randomaccessing is achieved by four function

called seekg(), seekp() and tellg(), tellp().

� seekg() and tellg() functions are used to set the getpointers. Similarly seekp() and tellp() are used to set theput_pointers.

� The seekg() and tellg() functions are used in ifstreamandseekp() and tellp() functions are used in ofstream

� If we use these function with fstreamobject then thetellg and tellp returns the same value and seekg andseekp works in the same way.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

SYNTAX

seekg() : istream & seekg(long); // form 1;istream & seekg(long,seek_dir); // form 2;

seekp() : ostream & seekp(long); // form 1;ostream & seekp(long,seek_dir); // form 2;

tellg() - returns long get_pointers;tellp() - returns long put_pointers;

fin.seekg(30); will move the get_pointer to byte no 30;fin.seekp(30); will move the put_pointer to byte no 30;

Ex

Seek_dir

ios::beg // refers to beginning of the file.ios::cur // refers to current of the file.ios::end // refers to end of file.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

EXAMPLES

fin.seekg(30,ios::beg); // goto byte no 30 from the beginning of the file;

fin.seekg(-5,ios::cur); // goto back 5 bytes from the current position;

fin.seekg(0,ios::end);; // goto the end of the file;

fin.seekg(-5,ios::end); // goto 5 byte back from end of file

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Basic operations on Binary Files� There are some operations performs on binary

files like..

� Searching

� Appending Data

� Inserting Data on Sorted File

� Deleting a Record

� Modifying Data

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Search Data from File using class#include<fstream.h>#include<conio.h>class student{char name[25];int rollno;public:void readdata();void printdata();int getrollno(){return(rollno);}};void student :: readdata(){cout<<endl<<"Enter Name ";cin>>name;cout<<endl<<"Enter Rollno ";

cin>>rollno;}void student :: printdata(){cout<<endl<<"Name = "<<name;cout<<endl<<"Rollno = "<<rollno;}void main(){char ch; int rno;fstream file;student s,t ;file.open("file.txt",ios::out|ios::in|ios::binary);clrscr();while(1){s.readdata();file.write((char *) &s, sizeof(s));cout<<"Do you Continue (Yes for Y or y) ";

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

cin>>ch;if (ch!='Y' && ch!='y') break;}cout<<endl<<"Enter Rollno to be search : ";cin>>rno;ch='n';file.seekg(0);while(!file.eof()){file.read((char *) &t, sizeof(t));if (t.getrollno()==rno){cout<<endl<<"Data Found "<<endl;t.printdata();ch='y';}}if (ch=='n')cout<<endl<<"Data Not Found ";getch();}

CONTINUE…

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Appending Data to the File.

� To append data in the file, the opened file in twomode.

� File is opened in output mode – ios::out

� File is opened in append mode – ios::app

� Once the file get opened in app mode, the old datawill retained and newdata get appended to the file

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Append Data in the File using class

#include<fstream.h>#include<conio.h>class student{char name[25];int rollno;public:void readdata();};void student :: readdata(){cout<<endl<<"Enter Name ";cin>>name;cout<<endl<<"Enter Rollno ";cin>>rollno;}

void main(){char ch; int rno;fstream file;student s,t ;file.open("file.txt",ios::app|ios::binary);clrscr();while(1){s.readdata();file.write((char *) &s, sizeof(s));cout<<"Do you Continue (Yes for Y or y) ";cin>>ch;if (ch!='Y' && ch!='y') break;}getch();}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Inserting Data in Sorted File� To inserted data in a sorted file, firstly its

appropriate position is determined and thenrecords in the file prior to this determined positionare copied to temporary file, followed by the newrecord to be inserted and then the rest of therecords fromthe file also copied.

� After that old file is delete and newfile rename asold file.

� So inserting in sorted file is done with followingsteps.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Continue…..� Copy the records prior to determined position to a

temporary file say.. temp.dat

� Append the newrecord in temp.dat

� Now append the rest of record of main file intothe temp.dat

� Delete the main file like student.dat

� remove(“student.dat”);

� rename the temp.dat as student.dat as

� rename(“temp.dat”,”student.dat”);

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Insert Data into Sorted file

#include<fstream.h>#include<stdio.h>#include<conio.h>class student{char name[25];int rollno;public:void readdata();int getrollno(){return(rollno);}};

void student :: readdata(){cout<<endl<<"Enter Name ";cin>>name;cout<<endl<<"Enter Rollno ";cin>>rollno;}int main(){fstream file,outfile;student prev,next,nrec;file.open("file.txt",ios::in|ios::binary);outfile.open("fil.txt",ios::out|ios::binary);nrec.readdata();clrscr();

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

while(1){file.read((char *) &next, sizeof(next));if (next.getrollno()==nrec.getrollno()) {cout<<endl<<"Record already exitst ";getch();return 0;}elseif (next.getrollno()>nrec.getrollno()) {outfile.write((char *) &nrec, sizeof(nrec));break;}else{prev=next;outfile.write((char *) &prev, sizeof(prev));}}

file.seekg(0);while(!file.eof()){file.read((char *) &next, sizeof(next));if (next.getrollno()>nrec.getrollno()){outfile.write((char *) &next, sizeof(next));}}remove("file.txt");rename("fil.txt","file.txt");getch();return 0;}

CONTINUE…

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Deleting a Record� Firstly determine the position of the record to be

deleted by performing search operation.

� Keep copying the record other than the record tobe deleted in a temporary file called temp.dat

� Do not copy the deleted record into the temp.dat

� Delete the orginal file as ..

� remove(“student.dat”);

� rename the temp.dat as student.dat as

� rename(“temp.dat”,”student.dat”);

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

PROGRAM

#include<fstream.h>#include<stdio.h>#include<conio.h>class student{char name[25];int rollno;public:void readdata();int getrollno(){return(rollno);}};void student :: readdata(){cout<<endl<<"Enter Rollno ";cin>>rollno;}

int main() {fstream file,outfile;student prev,next,drec;file.open("file.txt",ios::in|ios::binary);outfile.open("fi.txt",ios::out|ios::binary);drec.readdata();clrscr();while(!file.eof()){file.read((char *) &next, sizeof(next));if (next.getrollno()!=drec.getrollno()){outfile.write((char *) &next, sizeof(next));} }file.close();outfile.close();remove("file.txt");rename("fi.txt","file.txt");getch();return 0;}

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Modifying a Record� To modify a record, the file is opened in I/O

mode and an important step is performed thatgives the beginning address of record beingmodified.

� After the record is modified in memory, the filepointer is once again is placed in at beginningposition of this record and record is re-written.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

PROGRAM

#include<fstream.h>#include<stdio.h>#include<conio.h>class student{char name[25];int rollno;public:void modifydata();int getrollno(){return(rollno);} };void student :: modifydata(){cout<<endl<<"Enter Name ";cin>>name;cout<<endl<<"Enter Rollno ";cin>>rollno; }

int main() {int rno; long pos;fstream file;student mrec;file.open("file.txt",ios::in|ios::out|ios::binary);clrscr();cout<<endl<<"Enter Roll No to be modify ";cin>>rno;//mrec.readdata();clrscr();while(!file.eof()){pos=file.tellg();file.read((char *) &mrec, sizeof(mrec));if (mrec.getrollno()==rno){ mrec.modifydata();file.seekg(pos);file.write((char *) &mrec, sizeof(mrec));} }file.close();getch(); return 0; }

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Error Handling during File I/O� During file operation, errors may occurs – such as� File not exist. – for reading file� File already exist. – for writing file.� End of file occurs –� File can not be create – for less disk space� File can not be open – as corrupt file� To check for such errors and to ensure smooth

processing, C++ file stream inherits ‘Stream-state’ members from ios class, that stores the information on the status of the file being currently used.

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Flag bitseofbit 1 when end of file is encounter, 0 otherwisefailbit 1 when a not fatal error I/Oerror has

encounter 0 otherwisebadbit 1 when a fatal i/o error has occured, 0

otherwisegoodbit 0 value.

There are several error handling functions supported by theclass ios that help you read and process the status recordedin a file stream. Some error handling function are asfollows

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7

Error Handling Functionsint bad() Returns non-zero value, if an invalid operation is

attempted or any unrecoverable error has occured. if it is zero then possible to recover the error

int eof() Returns non-zero (true value) if end of file is encountered while reading otherwise return zero (false)

int fail() Returns non-zero (true) when input and output operation is failed.

int good() Returns non-zero (true) if no error has occured, This means all the above function are false

clear() Reset the error state so that further operation can be attempted.


Recommended