SlideShare a Scribd company logo
1 of 40
PRAVEEN M JIGAJINNI
PGT (Computer Science)
MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA,
Dc. Sc. & Engg.
email: praveenkumarjigajinni@yahoo.co.in
 Computer programs are associated to
work with files as it helps in storing data &
information permanently.
 File - itself a bunch of bytes stored on
some storage devices.
 In C++ this is achieved through a
component header file called fstream.h
 The I/O library manages two aspects- as
interface and for transfer of data.
 The library predefine a set of operations
for all file related handling through certain
classes.
A stream is a general term used to name flow of data.
Streams act as an interface between files and
programs.
A Stream is sequence of bytes.
They represent as a sequence of bytes and deals with
the flow of data.
Every stream is associated with a class having
member functions and operations for a particular kind
of data flow.
File  Program ( Input stream) - reads
Program  File (Output stream) – write
All designed into fstream.h and hence needs to be
included in all file handling programs.
Diagrammatically as shown in next slide
Hierarchy Diagram
FUNCTIONS OF FILE STREAM CLASSES
 filebuf – It sets the buffer to read and write, it contains
close() and open() member functions on it.
 fstreambase – this is the base class for fstream and,
ifstream and ofstream classes. therefore it provides the
common function to these classes. It also contains open()
and close() functions.
 ifstream – Being input class it provides input operations it
inherits the functions get( ), getline( ), read( ), and random
access functions seekg( ) and tellg( ) functions.
 ofstream – Being output class it provides output
operations it inherits put( ), write( ) and random access
functions seekp( ) and tellp( ) functions.
 fstream – it is an i/o class stream, it provides
simultaneous input and output operations.
A File can be stored in two ways
Text File
Binary File
Text Files : Stores information in ASCII characters. In text file
each line of text is terminated by with special character known
as EOL (End of Line) In text file some translations takes place
when this EOL character is read or written.
Binary File: it contains the information in the same format as
it is held in the memory. In binary file there is no delimiter for
a line. Also no translation occur in binary file. As a result
binary files are faster and easier for program to read and
write.
WHAT IS FILE MODE?
The File Mode describes how a file is to be used ; to
read from it, write to it, to append and so on
Syntax
Stream_object.open(“filename”,mode);
File Modes
ios::out: It open file in output mode (i.e write mode) and
place the file pointer in beginning, if file already exist it will
overwrite the file.
ios::in It open file in input mode(read mode) and permit
reading from the file.
ios::app It open the file in write mode, and place file pointer
at the end of file i.e to add new contents and retains previous
contents. If file does not exist it will create a new file.
ios::ate It open the file in write or read mode, and place file
pointer at the end of file i.e input/ output operations can
performed anywhere in the file.
ios::trunc It truncates the existing file (empties the file).
ios::nocreate If file does not exist this file mode ensures that
no file is created and open() fails.
 ios::noreplace If file does not exist, a new file gets created
but if the file already exists, the open() fails.
ios::binary Opens a file in binary mode.
Closing a FileClosing a File
 A File is closed by disconnecting it with the stream it is
associated with. The close( ) function is used to
accomplish this task.
Syntax:
Stream_object.close( );
Example :
fout.close();
Steps To Create A File
1. Declare an object of the desired file stream class(ifstream,
ofstream, or fstream)
2. Open the required file to be processed using constructor or
open function.
3. Process the file.
4. Close the file stream using the object of file stream.
eof ( ) Functioneof ( ) Function
This function determines the end-of-file by returning true(non-
zero) for end of file otherwise returning false(zero).
Syntax
Stream_object.eof( );
Example :
fout.eof( );
Text File Functions
get() – read a single character from text file and store in a
buffer.
e.g file.get(ch);
put() - writing a single character in textfile
e.g. file.put(ch);
getline() - read a line of text from text file store in a buffer.
e.g file.getline(s,80);
We can also use file>>ch for reading and file<<ch writing
in text file. But >> operator does not accept white spaces.
Program to create a text file using strings I/O
#include<fstream.h> //header file for file operations
void main()
{
char s[80], ch;
ofstream file(“myfile.txt”); //open myfile.txt in default output mode
do
{ cout<<”n enter line of text”;
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<”n more input y/n”;
cin>>ch;
}while(ch!=’n’||ch!=’N’);
file.close();
} //end of main
Program to read content of ‘myfile.txt’ and display it
on monitor.
#include<fstream.h> //header file for file operations
void main()
{
char ch;
ifstream file(“myfile.txt”); //open myfile.txt in default input mode
while(file)
{ file.get(ch) // read a
character from text file ‘
myfile.txt’
cout<<ch; // write a character in text file ‘myfile.txt ‘
}
file.close();
} //end of main
RELATED
TO
TEXT FILES
2/3 Marks QNO 4 (b)
1. Write a function in C++ to count the number of uppercase alphabets
present in a text file “BOOK.txt”
2. Write a function in C++ to count the number of alphabets present in a
text file “BOOK.txt”
3. Write a function in C++ to count the number of digits present in a text
file “BOOK.txt”
4. Write a function in C++ to count the number of white spaces present
in a text file “BOOK.txt”
5. Write a function in C++ to count the number of vowels present in a
text file “BOOK.txt”
6. Assume a text file “Test.txt” is already created. Using this file, write a
function to create three files “LOWER.TXT” which contains all the
lowercase vowels and “UPPER.TXT” which contains all the uppercase
vowels and “DIGIT.TXT” which contains all digits.
Binary File Functions
read( )- read a block of binary data or reads a fixed number of
bytes from the specified stream and store in a buffer.
Syntax : Stream_object.read((char *)& Object, sizeof(Object));
e.g file.read((char *)&s, sizeof(s));
write( ) – write a block of binary data or writes fixed number
of bytes from a specific memory location to the specified
stream.
Syntax : Stream_object.write((char *)& Object,
sizeof(Object));
e.g file.write((char *)&s, sizeof(s));
Binary File Functions
Note: Both functions take two arguments.
• The first is the address of variable, and the second is the
length of that variable in bytes. The address of variable must
be type cast to type char*(pointer to character type)
• The data written to a file using write( ) can only be read
accurately using read( ).
Program to create a binary file ‘student.dat’ using structure.
#include<fstream.h>
struct student
{
char name[15];
float percent;
};
void main()
{
ofstream fout;
char ch;
fout.open(“student.dat”, ios::out | ios:: binary);
clrscr();
student s;
if(!fout)
{
cout<<“File can’t be opened”;
exit(0);
}
do
{ cout<<”n
enter name of student”;
gets(s);
cout<<”n enter percentage”;
cin>>percent;
fout.write((char *)&s,sizeof(s)); // writing a record in a student.dat file
cout<<”n more record y/n”;
cin>>ch;
}while(ch!=’n’ || ch!=’N’);
fout.close();
}
Program to read a binary file ‘student.dat’ display records
on monitor.
#include<fstream.h>
struct student
{
char name[15];
float percent;
};
void main()
{
ifstream fin;
student s;
fin.open(“student.dat”,ios::in | ios:: binary);
fin.read((char *) &s, sizeof(student)); //read a record from file
‘student.dat’
CONTD....
while(file)
{
cout<<s.name;
cout<<“n has the percent: ”<<s.percent;
fin.read((char *) &s, sizeof(student));
}
fin.close();
}
RELATED
TO
BINARY FILES
3 MARKS
QNO 4 ( c )
QNO 4 ( C ) Write a function in c++ to search for details
(Phoneno and Calls) of those Phones which have more
than 800 calls from binary file “phones.dat”. Assuming
that this binary file contains records/ objects of class
Phone, which is defined below. CBSE 2012
class Phone
{
Char Phoneno[10]; int Calls;
public:
void Get() {gets(Phoneno); cin>>Calls;}
void Billing() { cout<<Phoneno<< “#”<<Calls<<endl;}
int GetCalls() {return Calls;}
};
Ans :
void Search()
{
Phone P;
fstream fin;
fin.open( “Phone.dat”, ios::binary| ios::in);
while(fin.read((char *)&P, sizeof(P)))
{
if(p.GetCalls() >800)
p.Billing();
}
Fin.close(); //ignore
}};
Write a function in C++ to add new objects at the bottom of a
binary file “STUDENT.DAT”, assuming the binary file is
containing the objects of the following class.
class STUD
{
int Rno;
char Name[20];
public:
void Enter()
{cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
Ans.
void searchbook(int bookno)
{ifstream ifile(“BOOK.DAT”,ios::in|ios::binary);
if(!ifile)
{cout<<”could not open BOOK.DAT file”; exit(-1);}
else
{BOOK b; int found=0;
while(ifile.read((char *)&b, sizeof(b)))
{if(b.RBno()==bookno)
{b.Display(); found=1; break;}
}
if(! found)
cout<<”record is not found “;
ifile.close();
}
}
Given a binary file PHONE.DAT, containing records of the
following class type
class Phonlist
{
char name[20];
char address[30];
char areacode[5];
char Phoneno[15];
public:
void Register()
void Show();
void CheckCode(char AC[])
{return(strcmp(areacode,AC);
};
Write a function TRANSFER( ) in C++, that would copy all
those records which are having areacode as “DEL” from
PHONE.DAT to PHONBACK.DAT.
Ans
void TRANSFER()
{
fstream File1,File2;
Phonelist P;
File1.open(“PHONE.DAT”, ios::binary|ios::in);
File2.open(“PHONEBACK.DAT”, ios::binary|ios::OUT)
while(File1.read((char *)&P, sizeof(P)))
{ if( p.CheckCode( “DEL”))
File2.write((char *)&P,sizeof(P)); }
File1.close();
File2.close();
}
File Pointer
The file pointer indicates the position in the file at which the
next input/output is to occur.
Moving the file pointer in a file for various operations viz
modification, deletion , searching etc. Following functions are
used
seekg(): It places the file pointer to the specified position in
input mode of file.
e.g file.seekg(p,ios::beg); or
file.seekg(-p,ios::end), or
file.seekg(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.
File Pointer
seekp(): It places the file pointer to the specified position in
output mode of file.
e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or
file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.
tellg(): This function returns the current working position of the
file pointer in the input mode.
e.g int p=file.tellg();
tellp(): This function returns the current working position of the
file pointer in the output mode.
e.f int p=file.tellp();
RELATED
TO
FILE POINTER
1 MARK
QNO 4 ( a )
4(a) Observe the program segment carefully and answer
the question that follows:
class stock
{
int Ino, Qty; Char Item[20];
public:
void Enter() { cin>>Ino; gets(Item); cin>>Qty;}
void issue(int Q) { Qty+=0;}
void Purchase(int Q) {Qty-=Q;}
int GetIno() { return Ino;}
};
void PurchaseItem(int Pino, int PQty)
{ fstream File;
File.open(“stock.dat”, ios::binary|ios::in|ios::out);
Stock s;
int success=0;
while(success= = 0 && File.read((char *)&s,sizeof(s)))
{
If(Pino= = ss.GetIno())
{
s.Purchase(PQty);
_______________________ // statement 1
_______________________ // statement 2
Success++;
}
}
if (success = =1)
cout<< “Purchase Updated”<<endl;
else
cout<< “Wrong Item No”<<endl;
File.close() ;
}
Ans
i) Statement 1 to position the file pointer to the appropriate
place so that the data updation is done for the required item.
File.seekp(File.tellg()-sizeof(stock);
OR
File.seekp(-sizeof(stock),ios::cur);
ii) Staement 2 to perform write operation so that the updation
is done in the binary file.
File.write((char *)&s, sizeof(s)); OR
File.write((char *)&s, sizeof(stock));
7 Data File Handling
7 Data File Handling

More Related Content

What's hot

What's hot (17)

Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
python file handling
python file handlingpython file handling
python file handling
 
File Pointers
File PointersFile Pointers
File Pointers
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
File Handling
File HandlingFile Handling
File Handling
 
Python file handling
Python file handlingPython file handling
Python file handling
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
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
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 

Viewers also liked

Viewers also liked (8)

6 Inheritance
6 Inheritance6 Inheritance
6 Inheritance
 
12 SQL
12 SQL12 SQL
12 SQL
 
Qno 2 (c)
Qno 2 (c)Qno 2 (c)
Qno 2 (c)
 
13 Boolean Algebra
13 Boolean Algebra13 Boolean Algebra
13 Boolean Algebra
 
Qno 3 (a)
Qno 3 (a)Qno 3 (a)
Qno 3 (a)
 
How to create simple fillable forms using word
How to create simple fillable forms using wordHow to create simple fillable forms using word
How to create simple fillable forms using word
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
How to create a simple, fillable form using Microsoft Word
How to create a simple, fillable form using Microsoft WordHow to create a simple, fillable form using Microsoft Word
How to create a simple, fillable form using Microsoft Word
 

Similar to 7 Data File Handling

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Deletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDeletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDipayan Sarkar
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfstudy material
 
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 referenceanuvayalil5525
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handlingDeepak Singh
 

Similar to 7 Data File Handling (20)

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File management in C++
File management in C++File management in C++
File management in C++
 
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
 
Deletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDeletion of a Record from a File - K Karun
Deletion of a Record from a File - K Karun
 
Data file handling
Data file handlingData file handling
Data file handling
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Filehandling
FilehandlingFilehandling
Filehandling
 
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
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
File operations
File operationsFile operations
File operations
 

More from Praveen M Jigajinni

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithmsPraveen M Jigajinni
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructorsPraveen M Jigajinni
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with pythonPraveen M Jigajinni
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingPraveen M Jigajinni
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow chartsPraveen M Jigajinni
 

More from Praveen M Jigajinni (20)

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithms
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Unit 3 MongDB
Unit 3 MongDBUnit 3 MongDB
Unit 3 MongDB
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
Chapter 9 python fundamentals
Chapter 9 python fundamentalsChapter 9 python fundamentals
Chapter 9 python fundamentals
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinking
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow charts
 
Chapter 5 boolean algebra
Chapter 5 boolean algebraChapter 5 boolean algebra
Chapter 5 boolean algebra
 
Chapter 4 number system
Chapter 4 number systemChapter 4 number system
Chapter 4 number system
 

Recently uploaded

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Recently uploaded (20)

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
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
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
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

7 Data File Handling

  • 1. PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg. email: praveenkumarjigajinni@yahoo.co.in
  • 2.
  • 3.  Computer programs are associated to work with files as it helps in storing data & information permanently.  File - itself a bunch of bytes stored on some storage devices.  In C++ this is achieved through a component header file called fstream.h  The I/O library manages two aspects- as interface and for transfer of data.  The library predefine a set of operations for all file related handling through certain classes.
  • 4. A stream is a general term used to name flow of data. Streams act as an interface between files and programs. A Stream is sequence of bytes. They represent as a sequence of bytes and deals with the flow of data. Every stream is associated with a class having member functions and operations for a particular kind of data flow. File  Program ( Input stream) - reads Program  File (Output stream) – write All designed into fstream.h and hence needs to be included in all file handling programs. Diagrammatically as shown in next slide
  • 5.
  • 7. FUNCTIONS OF FILE STREAM CLASSES  filebuf – It sets the buffer to read and write, it contains close() and open() member functions on it.  fstreambase – this is the base class for fstream and, ifstream and ofstream classes. therefore it provides the common function to these classes. It also contains open() and close() functions.  ifstream – Being input class it provides input operations it inherits the functions get( ), getline( ), read( ), and random access functions seekg( ) and tellg( ) functions.  ofstream – Being output class it provides output operations it inherits put( ), write( ) and random access functions seekp( ) and tellp( ) functions.  fstream – it is an i/o class stream, it provides simultaneous input and output operations.
  • 8. A File can be stored in two ways Text File Binary File Text Files : Stores information in ASCII characters. In text file each line of text is terminated by with special character known as EOL (End of Line) In text file some translations takes place when this EOL character is read or written. Binary File: it contains the information in the same format as it is held in the memory. In binary file there is no delimiter for a line. Also no translation occur in binary file. As a result binary files are faster and easier for program to read and write.
  • 9. WHAT IS FILE MODE? The File Mode describes how a file is to be used ; to read from it, write to it, to append and so on Syntax Stream_object.open(“filename”,mode); File Modes ios::out: It open file in output mode (i.e write mode) and place the file pointer in beginning, if file already exist it will overwrite the file. ios::in It open file in input mode(read mode) and permit reading from the file.
  • 10. ios::app It open the file in write mode, and place file pointer at the end of file i.e to add new contents and retains previous contents. If file does not exist it will create a new file. ios::ate It open the file in write or read mode, and place file pointer at the end of file i.e input/ output operations can performed anywhere in the file. ios::trunc It truncates the existing file (empties the file). ios::nocreate If file does not exist this file mode ensures that no file is created and open() fails.  ios::noreplace If file does not exist, a new file gets created but if the file already exists, the open() fails. ios::binary Opens a file in binary mode.
  • 11. Closing a FileClosing a File  A File is closed by disconnecting it with the stream it is associated with. The close( ) function is used to accomplish this task. Syntax: Stream_object.close( ); Example : fout.close();
  • 12. Steps To Create A File 1. Declare an object of the desired file stream class(ifstream, ofstream, or fstream) 2. Open the required file to be processed using constructor or open function. 3. Process the file. 4. Close the file stream using the object of file stream.
  • 13. eof ( ) Functioneof ( ) Function This function determines the end-of-file by returning true(non- zero) for end of file otherwise returning false(zero). Syntax Stream_object.eof( ); Example : fout.eof( );
  • 14. Text File Functions get() – read a single character from text file and store in a buffer. e.g file.get(ch); put() - writing a single character in textfile e.g. file.put(ch); getline() - read a line of text from text file store in a buffer. e.g file.getline(s,80); We can also use file>>ch for reading and file<<ch writing in text file. But >> operator does not accept white spaces.
  • 15. Program to create a text file using strings I/O #include<fstream.h> //header file for file operations void main() { char s[80], ch; ofstream file(“myfile.txt”); //open myfile.txt in default output mode do { cout<<”n enter line of text”; gets(s); //standard input file<<s; // write in a file myfile.txt cout<<”n more input y/n”; cin>>ch; }while(ch!=’n’||ch!=’N’); file.close(); } //end of main
  • 16. Program to read content of ‘myfile.txt’ and display it on monitor. #include<fstream.h> //header file for file operations void main() { char ch; ifstream file(“myfile.txt”); //open myfile.txt in default input mode while(file) { file.get(ch) // read a character from text file ‘ myfile.txt’ cout<<ch; // write a character in text file ‘myfile.txt ‘ } file.close(); } //end of main
  • 18. 1. Write a function in C++ to count the number of uppercase alphabets present in a text file “BOOK.txt” 2. Write a function in C++ to count the number of alphabets present in a text file “BOOK.txt” 3. Write a function in C++ to count the number of digits present in a text file “BOOK.txt” 4. Write a function in C++ to count the number of white spaces present in a text file “BOOK.txt” 5. Write a function in C++ to count the number of vowels present in a text file “BOOK.txt” 6. Assume a text file “Test.txt” is already created. Using this file, write a function to create three files “LOWER.TXT” which contains all the lowercase vowels and “UPPER.TXT” which contains all the uppercase vowels and “DIGIT.TXT” which contains all digits.
  • 19. Binary File Functions read( )- read a block of binary data or reads a fixed number of bytes from the specified stream and store in a buffer. Syntax : Stream_object.read((char *)& Object, sizeof(Object)); e.g file.read((char *)&s, sizeof(s)); write( ) – write a block of binary data or writes fixed number of bytes from a specific memory location to the specified stream. Syntax : Stream_object.write((char *)& Object, sizeof(Object)); e.g file.write((char *)&s, sizeof(s));
  • 20. Binary File Functions Note: Both functions take two arguments. • The first is the address of variable, and the second is the length of that variable in bytes. The address of variable must be type cast to type char*(pointer to character type) • The data written to a file using write( ) can only be read accurately using read( ).
  • 21. Program to create a binary file ‘student.dat’ using structure. #include<fstream.h> struct student { char name[15]; float percent; }; void main() { ofstream fout; char ch; fout.open(“student.dat”, ios::out | ios:: binary); clrscr(); student s; if(!fout) { cout<<“File can’t be opened”; exit(0); }
  • 22. do { cout<<”n enter name of student”; gets(s); cout<<”n enter percentage”; cin>>percent; fout.write((char *)&s,sizeof(s)); // writing a record in a student.dat file cout<<”n more record y/n”; cin>>ch; }while(ch!=’n’ || ch!=’N’); fout.close(); }
  • 23. Program to read a binary file ‘student.dat’ display records on monitor. #include<fstream.h> struct student { char name[15]; float percent; }; void main() { ifstream fin; student s; fin.open(“student.dat”,ios::in | ios:: binary); fin.read((char *) &s, sizeof(student)); //read a record from file ‘student.dat’ CONTD....
  • 24. while(file) { cout<<s.name; cout<<“n has the percent: ”<<s.percent; fin.read((char *) &s, sizeof(student)); } fin.close(); }
  • 26. QNO 4 ( C ) Write a function in c++ to search for details (Phoneno and Calls) of those Phones which have more than 800 calls from binary file “phones.dat”. Assuming that this binary file contains records/ objects of class Phone, which is defined below. CBSE 2012 class Phone { Char Phoneno[10]; int Calls; public: void Get() {gets(Phoneno); cin>>Calls;} void Billing() { cout<<Phoneno<< “#”<<Calls<<endl;} int GetCalls() {return Calls;} };
  • 27. Ans : void Search() { Phone P; fstream fin; fin.open( “Phone.dat”, ios::binary| ios::in); while(fin.read((char *)&P, sizeof(P))) { if(p.GetCalls() >800) p.Billing(); } Fin.close(); //ignore }};
  • 28. Write a function in C++ to add new objects at the bottom of a binary file “STUDENT.DAT”, assuming the binary file is containing the objects of the following class. class STUD { int Rno; char Name[20]; public: void Enter() {cin>>Rno;gets(Name);} void Display(){cout<<Rno<<Name<<endl;} };
  • 29. Ans. void searchbook(int bookno) {ifstream ifile(“BOOK.DAT”,ios::in|ios::binary); if(!ifile) {cout<<”could not open BOOK.DAT file”; exit(-1);} else {BOOK b; int found=0; while(ifile.read((char *)&b, sizeof(b))) {if(b.RBno()==bookno) {b.Display(); found=1; break;} } if(! found) cout<<”record is not found “; ifile.close(); } }
  • 30. Given a binary file PHONE.DAT, containing records of the following class type class Phonlist { char name[20]; char address[30]; char areacode[5]; char Phoneno[15]; public: void Register() void Show(); void CheckCode(char AC[]) {return(strcmp(areacode,AC); }; Write a function TRANSFER( ) in C++, that would copy all those records which are having areacode as “DEL” from PHONE.DAT to PHONBACK.DAT.
  • 31. Ans void TRANSFER() { fstream File1,File2; Phonelist P; File1.open(“PHONE.DAT”, ios::binary|ios::in); File2.open(“PHONEBACK.DAT”, ios::binary|ios::OUT) while(File1.read((char *)&P, sizeof(P))) { if( p.CheckCode( “DEL”)) File2.write((char *)&P,sizeof(P)); } File1.close(); File2.close(); }
  • 32. File Pointer The file pointer indicates the position in the file at which the next input/output is to occur. Moving the file pointer in a file for various operations viz modification, deletion , searching etc. Following functions are used seekg(): It places the file pointer to the specified position in input mode of file. e.g file.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur) i.e to move to p byte position from beginning, end or current position.
  • 33. File Pointer seekp(): It places the file pointer to the specified position in output mode of file. e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur) i.e to move to p byte position from beginning, end or current position. tellg(): This function returns the current working position of the file pointer in the input mode. e.g int p=file.tellg(); tellp(): This function returns the current working position of the file pointer in the output mode. e.f int p=file.tellp();
  • 35. 4(a) Observe the program segment carefully and answer the question that follows: class stock { int Ino, Qty; Char Item[20]; public: void Enter() { cin>>Ino; gets(Item); cin>>Qty;} void issue(int Q) { Qty+=0;} void Purchase(int Q) {Qty-=Q;} int GetIno() { return Ino;} };
  • 36. void PurchaseItem(int Pino, int PQty) { fstream File; File.open(“stock.dat”, ios::binary|ios::in|ios::out); Stock s; int success=0; while(success= = 0 && File.read((char *)&s,sizeof(s))) { If(Pino= = ss.GetIno()) { s.Purchase(PQty); _______________________ // statement 1 _______________________ // statement 2 Success++; } }
  • 37. if (success = =1) cout<< “Purchase Updated”<<endl; else cout<< “Wrong Item No”<<endl; File.close() ; }
  • 38. Ans i) Statement 1 to position the file pointer to the appropriate place so that the data updation is done for the required item. File.seekp(File.tellg()-sizeof(stock); OR File.seekp(-sizeof(stock),ios::cur); ii) Staement 2 to perform write operation so that the updation is done in the binary file. File.write((char *)&s, sizeof(s)); OR File.write((char *)&s, sizeof(stock));