SlideShare a Scribd company logo
1 of 20
Tutorial4us.comTutorial4us.com
FileFile
A file is a collection of related data stored inA file is a collection of related data stored in
a particular area on the disk . The data isa particular area on the disk . The data is
stored in disk using the concept of file .stored in disk using the concept of file .
File Handling in C++File Handling in C++
Tutorial4us.comTutorial4us.com
Why FileWhy File
Permanent storage of data : -Permanent storage of data : - (all the message(all the message
or value printed with help of any outputor value printed with help of any output
statements like printf , putchar are neverstatements like printf , putchar are never
available for future use ) .available for future use ) .
If there is a large amount of data generated asIf there is a large amount of data generated as
output by a program, storing that output in fileoutput by a program, storing that output in file
will help in easy handling /analysis of thewill help in easy handling /analysis of the
output , as user can see the whole output at anyoutput , as user can see the whole output at any
time even after complete execution of thetime even after complete execution of the
program.program.
Tutorial4us.comTutorial4us.com
If we need lot of data to be inputted, user cannotIf we need lot of data to be inputted, user cannot
keep on typing that again and again for repeatedkeep on typing that again and again for repeated
execution of program. In that case, all input dataexecution of program. In that case, all input data
can be once written in a file and then that filecan be once written in a file and then that file
can be easily used as the input file.can be easily used as the input file.
The transfer of input – data or output – data fromThe transfer of input – data or output – data from
one computer to another can be easily done byone computer to another can be easily done by
using files.using files.
Tutorial4us.comTutorial4us.com
Stream classesStream classes
Filebuf :-Filebuf :- its purpose is to set the file buffer to read andits purpose is to set the file buffer to read and
write . Containwrite . Contain openprotopenprot constant used in theconstant used in the open()open()
of file stream classes . Also containof file stream classes . Also contain close()close() andand open()open()
as method.as method.
Fstreambase :-Fstreambase :- provides operations common to the fileprovides operations common to the file
stream. Serves as a base for fstream, ifstream andstream. Serves as a base for fstream, ifstream and
ofsteram class. Containsofsteram class. Contains open()open() andand close()close() functionfunction
Ifstream :-Ifstream :- provides input operations. Contains open()provides input operations. Contains open()
with default input mode. Inherits the functionswith default input mode. Inherits the functions get()get(),,
getline()getline(),, read()read(),, seekg()seekg() andand tellg()tellg() function fromfunction from
istream.istream.
Tutorial4us.comTutorial4us.com
OfstreamOfstream :-:- provides output operations.provides output operations.
ContainsContains open()open() with default output mode.with default output mode.
InheritsInherits put()put(),, seekp()seekp(),, teelp()teelp() andand write()write()
function from ostream.function from ostream.
Fsream :-Fsream :- provides support for simultaneousprovides support for simultaneous
input and output operations. Containsinput and output operations. Contains open()open()
with default input mode. Inherits all the functionwith default input mode. Inherits all the function
fromfrom isteramisteram and ostream classes throughand ostream classes through
iostreamiostream
Tutorial4us.comTutorial4us.com
Opening file using open()Opening file using open()
The functionThe function open()open() can be used to opencan be used to open
multiple files that use the same stream object.multiple files that use the same stream object.
file-stream-class stream-object;file-stream-class stream-object;
stream-object . open (“filename”);stream-object . open (“filename”);
Tutorial4us.comTutorial4us.com
Open and close a fileOpen and close a file
eg:-eg:-
ofstream outfile; // create streamofstream outfile; // create stream
outfile . open (“DATA1”); // connect stream to DATA1outfile . open (“DATA1”); // connect stream to DATA1
…………………………………………………………....
…………………………………………………………....
outfile . Close(); //disconnect stream from DATA1outfile . Close(); //disconnect stream from DATA1
outfile . Open(“DATA2”); //connect stream to DATA2outfile . Open(“DATA2”); //connect stream to DATA2
…………………………………………………………....
…………………………………………………………....
outfile . close();outfile . close();
…………………………………………………………....
Tutorial4us.comTutorial4us.com
Mode of file openingMode of file opening
ios :: out = open file for write onlyios :: out = open file for write only
ios :: in = open file for read onlyios :: in = open file for read only
ios :: app = append to end-of-fileios :: app = append to end-of-file
ios :: ate = take us to the end of the file when itios :: ate = take us to the end of the file when it
is openedis opened
Both ios :: app and ios :: ate take us to the end of the fileBoth ios :: app and ios :: ate take us to the end of the file
when it is opened. The difference between the twowhen it is opened. The difference between the two
parameters is that the ios :: app allows us to add data toparameters is that the ios :: app allows us to add data to
the end of file only, while ios :: ate mode permits us to addthe end of file only, while ios :: ate mode permits us to add
data or to modify the existing data any where in the file.data or to modify the existing data any where in the file.
Tutorial4us.comTutorial4us.com
The mode can combine two or more parametersThe mode can combine two or more parameters
using the bitwiseusing the bitwise OROR operator (symbol |)operator (symbol |)
eg :-eg :-
fstream file;fstream file;
file . Open(“ data . txt”, ios :: out | ios :: in);file . Open(“ data . txt”, ios :: out | ios :: in);
Tutorial4us.comTutorial4us.com
File pointerFile pointer
Each file have two associated pointers known asEach file have two associated pointers known as
the file pointers. One of them is called the inputthe file pointers. One of them is called the input
pointer (or get pointer) and the other is called thepointer (or get pointer) and the other is called the
output pointer (or put pointer). The input pointeroutput pointer (or put pointer). The input pointer
is used for reading the contents of a given fileis used for reading the contents of a given file
location and the output pointer is used for writinglocation and the output pointer is used for writing
to a given file location.to a given file location.
Tutorial4us.comTutorial4us.com
Function for manipulationFunction for manipulation
of file pointerof file pointer
When we want to move file pointer to desiredWhen we want to move file pointer to desired
position then use these function for manage theposition then use these function for manage the
file pointers.file pointers.
Seekg () = moves get pointer (input) to aSeekg () = moves get pointer (input) to a
specified locationspecified location
Seekp () = moves put pointer (output) to aSeekp () = moves put pointer (output) to a
specified locationspecified location
tellg () = gives the current position of the get pointertellg () = gives the current position of the get pointer
tellp () = gives the current position of the put pointertellp () = gives the current position of the put pointer
Tutorial4us.comTutorial4us.com
fout . seekg(0, ios :: beg) -- go to startfout . seekg(0, ios :: beg) -- go to start
fout . seekg(0, ios :: cur) -- stay at current positionfout . seekg(0, ios :: cur) -- stay at current position
fout . seekg(0, ios :: end) -- go to the end of filefout . seekg(0, ios :: end) -- go to the end of file
fout . seekg(m, ios :: beg) -- move to m+1 byte in the filefout . seekg(m, ios :: beg) -- move to m+1 byte in the file
fout . seekg(m, ios :: cur) -- go forward by m bytes fromfout . seekg(m, ios :: cur) -- go forward by m bytes from
the current positionthe current position
fout . seekg(-m, ios :: cur) -- go backward by m bytesfout . seekg(-m, ios :: cur) -- go backward by m bytes
from the current positionfrom the current position
fout . seekg(-m, ios :: end) -- go backward by m bytesfout . seekg(-m, ios :: end) -- go backward by m bytes
from the endfrom the end
Tutorial4us.comTutorial4us.com
put() and get() functionput() and get() function
The function put() write a single character to theThe function put() write a single character to the
associated stream. Similarly, the function get()associated stream. Similarly, the function get()
reads a single character from the associatedreads a single character from the associated
stream.stream.
Tutorial4us.comTutorial4us.com
read() and write() functionread() and write() function
file . read ((char *)&V , sizeof (V));file . read ((char *)&V , sizeof (V));
file . Write ((char *)&V , sizeof (V));file . Write ((char *)&V , sizeof (V));
These function take two arguments. The first isThese function take two arguments. The first is
the address of the variable V , and the second isthe address of the variable V , and the second is
the length of that variable in bytes . The addressthe length of that variable in bytes . The address
of variable must be cast to type char * (i.e pointerof variable must be cast to type char * (i.e pointer
to character type) .to character type) .
Tutorial4us.comTutorial4us.com
Program for file handlingProgram for file handling
#include< iostream . h>#include< iostream . h>
#include< conio .h>#include< conio .h>
#include< fstream . h>#include< fstream . h>
Class studentClass student
{{
Public:Public:
Struct stuStruct stu
{{
char name[20];char name[20];
int roll;int roll;
}s;}s;
Void put_data();Void put_data();
Void get_data();Void get_data();
};}; Tutorial4us.comTutorial4us.com
void student :: put_data()void student :: put_data()
{{
cout<<"enter name ";cout<<"enter name ";
cin>>s. name;cin>>s. name;
cout<<"enter roll ";cout<<"enter roll ";
cin>>s. roll;cin>>s. roll;
file. Open ("hit. txt“ , ios :: out | ios :: app);file. Open ("hit. txt“ , ios :: out | ios :: app);
file. write ((char *)this, sizeof (student));file. write ((char *)this, sizeof (student));
file. close();file. close();
getch();getch();
get_data();get_data();
}}
Tutorial4us.comTutorial4us.com
void student :: get_data()void student :: get_data()
{{
int temp;int temp;
cout<<"enter roll no. ";cout<<"enter roll no. ";
cin >>temp;cin >>temp;
fstream file;fstream file;
file. open ("hit . txt", ios :: in);file. open ("hit . txt", ios :: in);
file.seekg(0,ios::beg);file.seekg(0,ios::beg);
While (file . read ((char *) this, sizeof (student)))While (file . read ((char *) this, sizeof (student)))
{{
If (temp==s. roll)If (temp==s. roll)
{{
cout<<"student name "<< s . name<<"n";cout<<"student name "<< s . name<<"n";
cout<<"student roll "<< s . roll;cout<<"student roll "<< s . roll;
}}
}}
getch ();getch (); Tutorial4us.comTutorial4us.com
void main()void main()
{{
clrscr();clrscr();
student st;student st;
st .put_data();st .put_data();
}}
Tutorial4us.comTutorial4us.com
http://www.tutorial4us.com/cprogramming/c-file-handlinghttp://www.tutorial4us.com/cprogramming/c-file-handling

More Related Content

What's hot

Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in cyazad dumasia
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 

What's hot (20)

Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
file handling c++
file handling c++file handling c++
file handling c++
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
File in C language
File in C languageFile in C language
File in C language
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
File handling-c
File handling-cFile handling-c
File handling-c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Files in c++
Files in c++Files in c++
Files in c++
 
Arrays
ArraysArrays
Arrays
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 

Viewers also liked

Viewers also liked (20)

File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
File Pointers
File PointersFile Pointers
File Pointers
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and output
 
Handling computer files
Handling computer filesHandling computer files
Handling computer files
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
14 file handling
14 file handling14 file handling
14 file handling
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
8 header files
8 header files8 header files
8 header files
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritance
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
C++ file
C++ fileC++ file
C++ file
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
 

Similar to File handling in C++

Similar to File handling in C++ (20)

cpp-file-handling
cpp-file-handlingcpp-file-handling
cpp-file-handling
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
working with files
working with filesworking with files
working with files
 
working with files
working with filesworking with files
working with files
 
File management in C++
File management in C++File management in C++
File management in C++
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Unit 8
Unit 8Unit 8
Unit 8
 
data file handling
data file handlingdata file handling
data file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
File Handling
File HandlingFile Handling
File Handling
 

More from Hitesh Kumar

Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Hitesh Kumar
 
HTML Interview Questions | Basic Html Interview Questions
HTML Interview Questions | Basic Html Interview QuestionsHTML Interview Questions | Basic Html Interview Questions
HTML Interview Questions | Basic Html Interview QuestionsHitesh Kumar
 
Fibonacci Series Program in C++
Fibonacci Series Program in C++Fibonacci Series Program in C++
Fibonacci Series Program in C++Hitesh Kumar
 
CSS Interview Questions for Fresher and Experience
CSS Interview Questions for Fresher and Experience CSS Interview Questions for Fresher and Experience
CSS Interview Questions for Fresher and Experience Hitesh Kumar
 
Factorial Program in C
Factorial Program in CFactorial Program in C
Factorial Program in CHitesh Kumar
 
Prime number program in C
Prime number program in CPrime number program in C
Prime number program in CHitesh Kumar
 
Top JSON Interview Questions for Freshers
Top JSON Interview Questions for FreshersTop JSON Interview Questions for Freshers
Top JSON Interview Questions for FreshersHitesh Kumar
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleHitesh Kumar
 
Fibonacci series c++
Fibonacci series c++Fibonacci series c++
Fibonacci series c++Hitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Encapsulation in C++
Encapsulation in C++Encapsulation in C++
Encapsulation in C++Hitesh Kumar
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in javaHitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in javaHitesh Kumar
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Main method in java
Main method in javaMain method in java
Main method in javaHitesh Kumar
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 

More from Hitesh Kumar (20)

Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++
 
HTML Interview Questions | Basic Html Interview Questions
HTML Interview Questions | Basic Html Interview QuestionsHTML Interview Questions | Basic Html Interview Questions
HTML Interview Questions | Basic Html Interview Questions
 
Fibonacci Series Program in C++
Fibonacci Series Program in C++Fibonacci Series Program in C++
Fibonacci Series Program in C++
 
CSS Interview Questions for Fresher and Experience
CSS Interview Questions for Fresher and Experience CSS Interview Questions for Fresher and Experience
CSS Interview Questions for Fresher and Experience
 
Factorial Program in C
Factorial Program in CFactorial Program in C
Factorial Program in C
 
Prime number program in C
Prime number program in CPrime number program in C
Prime number program in C
 
Top JSON Interview Questions for Freshers
Top JSON Interview Questions for FreshersTop JSON Interview Questions for Freshers
Top JSON Interview Questions for Freshers
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of Example
 
Fibonacci series c++
Fibonacci series c++Fibonacci series c++
Fibonacci series c++
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Encapsulation in C++
Encapsulation in C++Encapsulation in C++
Encapsulation in C++
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Ternary operator
Ternary operatorTernary operator
Ternary operator
 
Main method in java
Main method in javaMain method in java
Main method in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

File handling in C++

  • 2. FileFile A file is a collection of related data stored inA file is a collection of related data stored in a particular area on the disk . The data isa particular area on the disk . The data is stored in disk using the concept of file .stored in disk using the concept of file . File Handling in C++File Handling in C++ Tutorial4us.comTutorial4us.com
  • 3. Why FileWhy File Permanent storage of data : -Permanent storage of data : - (all the message(all the message or value printed with help of any outputor value printed with help of any output statements like printf , putchar are neverstatements like printf , putchar are never available for future use ) .available for future use ) . If there is a large amount of data generated asIf there is a large amount of data generated as output by a program, storing that output in fileoutput by a program, storing that output in file will help in easy handling /analysis of thewill help in easy handling /analysis of the output , as user can see the whole output at anyoutput , as user can see the whole output at any time even after complete execution of thetime even after complete execution of the program.program. Tutorial4us.comTutorial4us.com
  • 4. If we need lot of data to be inputted, user cannotIf we need lot of data to be inputted, user cannot keep on typing that again and again for repeatedkeep on typing that again and again for repeated execution of program. In that case, all input dataexecution of program. In that case, all input data can be once written in a file and then that filecan be once written in a file and then that file can be easily used as the input file.can be easily used as the input file. The transfer of input – data or output – data fromThe transfer of input – data or output – data from one computer to another can be easily done byone computer to another can be easily done by using files.using files. Tutorial4us.comTutorial4us.com
  • 5. Stream classesStream classes Filebuf :-Filebuf :- its purpose is to set the file buffer to read andits purpose is to set the file buffer to read and write . Containwrite . Contain openprotopenprot constant used in theconstant used in the open()open() of file stream classes . Also containof file stream classes . Also contain close()close() andand open()open() as method.as method. Fstreambase :-Fstreambase :- provides operations common to the fileprovides operations common to the file stream. Serves as a base for fstream, ifstream andstream. Serves as a base for fstream, ifstream and ofsteram class. Containsofsteram class. Contains open()open() andand close()close() functionfunction Ifstream :-Ifstream :- provides input operations. Contains open()provides input operations. Contains open() with default input mode. Inherits the functionswith default input mode. Inherits the functions get()get(),, getline()getline(),, read()read(),, seekg()seekg() andand tellg()tellg() function fromfunction from istream.istream. Tutorial4us.comTutorial4us.com
  • 6. OfstreamOfstream :-:- provides output operations.provides output operations. ContainsContains open()open() with default output mode.with default output mode. InheritsInherits put()put(),, seekp()seekp(),, teelp()teelp() andand write()write() function from ostream.function from ostream. Fsream :-Fsream :- provides support for simultaneousprovides support for simultaneous input and output operations. Containsinput and output operations. Contains open()open() with default input mode. Inherits all the functionwith default input mode. Inherits all the function fromfrom isteramisteram and ostream classes throughand ostream classes through iostreamiostream Tutorial4us.comTutorial4us.com
  • 7. Opening file using open()Opening file using open() The functionThe function open()open() can be used to opencan be used to open multiple files that use the same stream object.multiple files that use the same stream object. file-stream-class stream-object;file-stream-class stream-object; stream-object . open (“filename”);stream-object . open (“filename”); Tutorial4us.comTutorial4us.com
  • 8. Open and close a fileOpen and close a file eg:-eg:- ofstream outfile; // create streamofstream outfile; // create stream outfile . open (“DATA1”); // connect stream to DATA1outfile . open (“DATA1”); // connect stream to DATA1 ………………………………………………………….... ………………………………………………………….... outfile . Close(); //disconnect stream from DATA1outfile . Close(); //disconnect stream from DATA1 outfile . Open(“DATA2”); //connect stream to DATA2outfile . Open(“DATA2”); //connect stream to DATA2 ………………………………………………………….... ………………………………………………………….... outfile . close();outfile . close(); ………………………………………………………….... Tutorial4us.comTutorial4us.com
  • 9. Mode of file openingMode of file opening ios :: out = open file for write onlyios :: out = open file for write only ios :: in = open file for read onlyios :: in = open file for read only ios :: app = append to end-of-fileios :: app = append to end-of-file ios :: ate = take us to the end of the file when itios :: ate = take us to the end of the file when it is openedis opened Both ios :: app and ios :: ate take us to the end of the fileBoth ios :: app and ios :: ate take us to the end of the file when it is opened. The difference between the twowhen it is opened. The difference between the two parameters is that the ios :: app allows us to add data toparameters is that the ios :: app allows us to add data to the end of file only, while ios :: ate mode permits us to addthe end of file only, while ios :: ate mode permits us to add data or to modify the existing data any where in the file.data or to modify the existing data any where in the file. Tutorial4us.comTutorial4us.com
  • 10. The mode can combine two or more parametersThe mode can combine two or more parameters using the bitwiseusing the bitwise OROR operator (symbol |)operator (symbol |) eg :-eg :- fstream file;fstream file; file . Open(“ data . txt”, ios :: out | ios :: in);file . Open(“ data . txt”, ios :: out | ios :: in); Tutorial4us.comTutorial4us.com
  • 11. File pointerFile pointer Each file have two associated pointers known asEach file have two associated pointers known as the file pointers. One of them is called the inputthe file pointers. One of them is called the input pointer (or get pointer) and the other is called thepointer (or get pointer) and the other is called the output pointer (or put pointer). The input pointeroutput pointer (or put pointer). The input pointer is used for reading the contents of a given fileis used for reading the contents of a given file location and the output pointer is used for writinglocation and the output pointer is used for writing to a given file location.to a given file location. Tutorial4us.comTutorial4us.com
  • 12. Function for manipulationFunction for manipulation of file pointerof file pointer When we want to move file pointer to desiredWhen we want to move file pointer to desired position then use these function for manage theposition then use these function for manage the file pointers.file pointers. Seekg () = moves get pointer (input) to aSeekg () = moves get pointer (input) to a specified locationspecified location Seekp () = moves put pointer (output) to aSeekp () = moves put pointer (output) to a specified locationspecified location tellg () = gives the current position of the get pointertellg () = gives the current position of the get pointer tellp () = gives the current position of the put pointertellp () = gives the current position of the put pointer Tutorial4us.comTutorial4us.com
  • 13. fout . seekg(0, ios :: beg) -- go to startfout . seekg(0, ios :: beg) -- go to start fout . seekg(0, ios :: cur) -- stay at current positionfout . seekg(0, ios :: cur) -- stay at current position fout . seekg(0, ios :: end) -- go to the end of filefout . seekg(0, ios :: end) -- go to the end of file fout . seekg(m, ios :: beg) -- move to m+1 byte in the filefout . seekg(m, ios :: beg) -- move to m+1 byte in the file fout . seekg(m, ios :: cur) -- go forward by m bytes fromfout . seekg(m, ios :: cur) -- go forward by m bytes from the current positionthe current position fout . seekg(-m, ios :: cur) -- go backward by m bytesfout . seekg(-m, ios :: cur) -- go backward by m bytes from the current positionfrom the current position fout . seekg(-m, ios :: end) -- go backward by m bytesfout . seekg(-m, ios :: end) -- go backward by m bytes from the endfrom the end Tutorial4us.comTutorial4us.com
  • 14. put() and get() functionput() and get() function The function put() write a single character to theThe function put() write a single character to the associated stream. Similarly, the function get()associated stream. Similarly, the function get() reads a single character from the associatedreads a single character from the associated stream.stream. Tutorial4us.comTutorial4us.com
  • 15. read() and write() functionread() and write() function file . read ((char *)&V , sizeof (V));file . read ((char *)&V , sizeof (V)); file . Write ((char *)&V , sizeof (V));file . Write ((char *)&V , sizeof (V)); These function take two arguments. The first isThese function take two arguments. The first is the address of the variable V , and the second isthe address of the variable V , and the second is the length of that variable in bytes . The addressthe length of that variable in bytes . The address of variable must be cast to type char * (i.e pointerof variable must be cast to type char * (i.e pointer to character type) .to character type) . Tutorial4us.comTutorial4us.com
  • 16. Program for file handlingProgram for file handling #include< iostream . h>#include< iostream . h> #include< conio .h>#include< conio .h> #include< fstream . h>#include< fstream . h> Class studentClass student {{ Public:Public: Struct stuStruct stu {{ char name[20];char name[20]; int roll;int roll; }s;}s; Void put_data();Void put_data(); Void get_data();Void get_data(); };}; Tutorial4us.comTutorial4us.com
  • 17. void student :: put_data()void student :: put_data() {{ cout<<"enter name ";cout<<"enter name "; cin>>s. name;cin>>s. name; cout<<"enter roll ";cout<<"enter roll "; cin>>s. roll;cin>>s. roll; file. Open ("hit. txt“ , ios :: out | ios :: app);file. Open ("hit. txt“ , ios :: out | ios :: app); file. write ((char *)this, sizeof (student));file. write ((char *)this, sizeof (student)); file. close();file. close(); getch();getch(); get_data();get_data(); }} Tutorial4us.comTutorial4us.com
  • 18. void student :: get_data()void student :: get_data() {{ int temp;int temp; cout<<"enter roll no. ";cout<<"enter roll no. "; cin >>temp;cin >>temp; fstream file;fstream file; file. open ("hit . txt", ios :: in);file. open ("hit . txt", ios :: in); file.seekg(0,ios::beg);file.seekg(0,ios::beg); While (file . read ((char *) this, sizeof (student)))While (file . read ((char *) this, sizeof (student))) {{ If (temp==s. roll)If (temp==s. roll) {{ cout<<"student name "<< s . name<<"n";cout<<"student name "<< s . name<<"n"; cout<<"student roll "<< s . roll;cout<<"student roll "<< s . roll; }} }} getch ();getch (); Tutorial4us.comTutorial4us.com
  • 19. void main()void main() {{ clrscr();clrscr(); student st;student st; st .put_data();st .put_data(); }} Tutorial4us.comTutorial4us.com