SlideShare a Scribd company logo
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

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 worldtcurdt
 
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 wheeltcurdt
 
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 LanguageESUG
 
File Transfer Through Sockets
File Transfer Through SocketsFile Transfer Through Sockets
File Transfer Through Socketsadil raja
 
03 standard class library
03 standard class library03 standard class library
03 standard class libraryeleksdev
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'Gaurav Garg
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Ken Kousen
 
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 CMahendra Yadav
 
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...Data Con LA
 

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-phpapp01Rex Joe
 
Sample file processing
Sample file processingSample file processing
Sample file processingIssay Meii
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handlingsparkishpearl
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Files in c
Files in cFiles in c
Files in cTanujaA3
 
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.pptmuhazamali0
 
Programming in C
Programming in CProgramming in C
Programming in Csujathavvv
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
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.pdffcaindore
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c languageHarish Gyanani
 

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

Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxDenish Jangid
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfjoachimlavalley1
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxCapitolTechU
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...Nguyen Thanh Tu Collection
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxJenilouCasareno
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfYibeltalNibretu
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chipsGeoBlogs
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptSourabh Kumar
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxRaedMohamed3
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleCeline George
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345beazzy04
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxbennyroshan06
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesRased Khan
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfDr. M. Kumaresan Hort.
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online PresentationGDSCYCCE
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...Denish Jangid
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringDenish Jangid
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersPedroFerreira53928
 

Recently uploaded (20)

Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdf
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 

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)