SlideShare a Scribd company logo
1 of 19
Download to read offline
BASIC FILE OPERATIONS
IN BINARY FILES
Introduction
 The only difference is that while working with binary files, you do
need to prefix file modes with ios::binary at the time of opening the
file.
 You have learnt how to create files (open them in ios::out or ios::app
mode which will create a file if it doesn't exist already),
 To read records from binary files (call read() function through
stream object to which file is attached),
 To write records in binary files (call write() function through stream
object which file is attached).
BASIC OPERATIONS IN A BINARY FILE
Searching
Appending data
Inserting data in sorted file
Modifying data
Deleting a record
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.
#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<<"Rollno: "<<rollno<<"tName: "<<name<<"n";
cout<<"Marks: "<<marks<<"tGrade: "<<grade<<"n";
}
int getrno()
{
return rollno;
}
} stud1;
// class student created
//Example : To search a record in a file
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 filen";
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);
}
fio.close();
getch();
}
OUTPUT
Appending Data in C++
 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.
// Example : to append data in a file in C++
class student
{
:// class definition
} stud1;
void main()
{
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();
}
OUTPUT
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.
Inserting Data in Sorted File
STEPS :
(Open the file in read mode(marks.dat) and open temp.dat in write mode)
 i) Determining the appropriate position.
 (ii) Copy the records prior to determined position to a temporary file say
temp.dat.
 (iii) Append the new record in the temporary file temp.dat.
 (iv) Now append the rest of the records in temporary file temp.dat.
 (v) Delete the file marks.dat by using the following code.
remove("marks.dat");
 (vi) Now, rename the file temp.dat as marks.dat as follows :
rename("temp.dat", "marks.dat");
//EXAMPLE to insert a new record in a sorted file
class student
{
: // class definition
} stud1;
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 insertedn";
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)); }
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();
}
OUTPUT
Deleting a record from a File
STEPS :
To delete a record, following procedure is carried out :
 (i) Firstly, determine the position of the record to be deleted, by performing
a search in the file.
 (ii) Keep copying the records other than the record to be deleted in a
temporary file say temp.dat.
 (iii) Do not copy the record to be deleted to temporary file, temp.dat.
 (iv) Copy rest of the records to temp.dat.
 (v) Delete original file say marks.dat as :
remove("marks.dat");
 (vi) Rename temp.dat as marks.dat as :
rename("temp.dat", "marks.dat");
//EXAMPLE to delete a record from a file
class student
{
: // class definition
} stud1;
void main()
{
clrscr();
ifstream fio(“marks.dat",ios::in);
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*)&stud1,sizeof(stud1));
if(stud1.getrno()==rno)
{
stud1.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*)&stud1,sizeof(s1));
}
else
file.write((char*)&stud1,sizeof(stud1));
}
if(found=='f')
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*)&stud1,sizeof(stud1));
if(fio.eof())
break;
stud1.putdata();
}
fio.close();
getch();
}
Modifying a record in a File
STEPS :
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.
//EXAMPLE to insert a new record in a sorted file
class student
{
:
void modify();
}stud1;
void main( )
{
clrscr();
fstream fio("marks.dat", ios::in | ios::out); /* Read rollno whose data is to be modified */
long pos;
while(!fio.eof())
{
pos = fio.tellg() // determine the beginning position of record
fio.read((char *) & stud1, sizeof(stud1));
if(stud1.getrno() == rollno) // 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
}
}
}
Created by
SATHASIVAN H
(PGT in Computer Science)

More Related Content

What's hot

03 standard class library
03 standard class library03 standard class library
03 standard class library
eleksdev
 

What's hot (20)

C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
Python lec4
Python lec4Python lec4
Python lec4
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real world
 
Python lec5
Python lec5Python lec5
Python lec5
 
Jakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheelJakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheel
 
Mod04 debuggers
Mod04 debuggersMod04 debuggers
Mod04 debuggers
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Lab4
Lab4Lab4
Lab4
 
Linux basic1&amp;2
Linux basic1&amp;2Linux basic1&amp;2
Linux basic1&amp;2
 
srgoc
srgocsrgoc
srgoc
 
File Transfer Through Sockets
File Transfer Through SocketsFile Transfer Through Sockets
File Transfer Through Sockets
 
03 standard class library
03 standard class library03 standard class library
03 standard class library
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Similar to Basic file operations CBSE class xii ln 7

Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Sample file processing
Sample file processingSample file processing
Sample file processing
Issay Meii
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
RutujaTandalwade
 
Modify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdfModify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdf
fcaindore
 

Similar to Basic file operations CBSE class xii ln 7 (20)

Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
Sample file processing
Sample file processingSample file processing
Sample file processing
 
file handling c++
file handling c++file handling c++
file handling c++
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Files in c
Files in cFiles in c
Files in c
 
Unit5
Unit5Unit5
Unit5
 
File Handling in C++ full ppt slide presentation.ppt
File Handling in C++ full ppt slide presentation.pptFile Handling in C++ full ppt slide presentation.ppt
File Handling in C++ full ppt slide presentation.ppt
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Modify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdfModify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdf
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File management
File managementFile management
File management
 
5 Structure & File.pptx
5 Structure & File.pptx5 Structure & File.pptx
5 Structure & File.pptx
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
Files and streams
Files and streamsFiles and streams
Files and streams
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 

Basic file operations CBSE class xii ln 7

  • 2. Introduction  The only difference is that while working with binary files, you do need to prefix file modes with ios::binary at the time of opening the file.  You have learnt how to create files (open them in ios::out or ios::app mode which will create a file if it doesn't exist already),  To read records from binary files (call read() function through stream object to which file is attached),  To write records in binary files (call write() function through stream object which file is attached).
  • 3. BASIC OPERATIONS IN A BINARY FILE Searching Appending data Inserting data in sorted file Modifying data Deleting a record
  • 4. 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.
  • 5. #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<<"Rollno: "<<rollno<<"tName: "<<name<<"n"; cout<<"Marks: "<<marks<<"tGrade: "<<grade<<"n"; } int getrno() { return rollno; } } stud1; // class student created
  • 6. //Example : To search a record in a file 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 filen"; 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); } fio.close(); getch(); }
  • 8. Appending Data in C++  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.
  • 9. // Example : to append data in a file in C++ class student { :// class definition } stud1; void main() { 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(); }
  • 11. 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.
  • 12. Inserting Data in Sorted File STEPS : (Open the file in read mode(marks.dat) and open temp.dat in write mode)  i) Determining the appropriate position.  (ii) Copy the records prior to determined position to a temporary file say temp.dat.  (iii) Append the new record in the temporary file temp.dat.  (iv) Now append the rest of the records in temporary file temp.dat.  (v) Delete the file marks.dat by using the following code. remove("marks.dat");  (vi) Now, rename the file temp.dat as marks.dat as follows : rename("temp.dat", "marks.dat");
  • 13. //EXAMPLE to insert a new record in a sorted file class student { : // class definition } stud1; 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 insertedn"; 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)); } 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(); }
  • 15. Deleting a record from a File STEPS : To delete a record, following procedure is carried out :  (i) Firstly, determine the position of the record to be deleted, by performing a search in the file.  (ii) Keep copying the records other than the record to be deleted in a temporary file say temp.dat.  (iii) Do not copy the record to be deleted to temporary file, temp.dat.  (iv) Copy rest of the records to temp.dat.  (v) Delete original file say marks.dat as : remove("marks.dat");  (vi) Rename temp.dat as marks.dat as : rename("temp.dat", "marks.dat");
  • 16. //EXAMPLE to delete a record from a file class student { : // class definition } stud1; void main() { clrscr(); ifstream fio(“marks.dat",ios::in); 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*)&stud1,sizeof(stud1)); if(stud1.getrno()==rno) { stud1.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*)&stud1,sizeof(s1)); } else file.write((char*)&stud1,sizeof(stud1)); } if(found=='f') 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*)&stud1,sizeof(stud1)); if(fio.eof()) break; stud1.putdata(); } fio.close(); getch(); }
  • 17. Modifying a record in a File STEPS : 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.
  • 18. //EXAMPLE to insert a new record in a sorted file class student { : void modify(); }stud1; void main( ) { clrscr(); fstream fio("marks.dat", ios::in | ios::out); /* Read rollno whose data is to be modified */ long pos; while(!fio.eof()) { pos = fio.tellg() // determine the beginning position of record fio.read((char *) & stud1, sizeof(stud1)); if(stud1.getrno() == rollno) // 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 } } }
  • 19. Created by SATHASIVAN H (PGT in Computer Science)