SlideShare a Scribd company logo
Prepared by : SELVIN JOSY BAI.S
 Use of header file fstream.h
 Types of stream objects
 open() and close() functions
 File mode constants
 Reading and writing characters from / to
disk
 Detecting end of file
 Reading and writing objects from / to disk
 File pointers for Random Access
 Error handling functions
Most computer programs work with files.
Word processors create document files.
Database programs create files of information.
Compilers read source files and generate executable
files.
In C++, file input / output facilities are implemented
through a component header file of C++ standard
library. This header file is fstream.h.
File Stream Read data
A File stream act as an
interface between the
program and the files.
•The stream that
supplies data to the
program is known as
input stream.
•The stream that
receives data from the
program is known as
output stream.
Disk
Files
Program
Data input
Write data
Data
output
Output stream
Input stream
CLASSES FOR FILE STREAM OPERATIONS
ios
istream streambuf ostream
iostream
ifstream fstream ofstream filebuf
fstreambase
…………………………………………………………………………………………………………………………………………….
iostreamfilefstreamfile
Using fstream.h
A stream is a sequence of bytes.
It is a general name given to a flow of data.
Different streams are used to represent
different kinds of data flow.
ifstream class represents input disk files.
ofstream class represents output disk files.
fstream – for both input and output
Member functions of these classes are used to
perform I/O operations.
Different Classes and its functions
Class Functions
filebuf It sets the file buffers to read and write.
Member functions : open(), close()
fstreambase This is the base class for fstream, ifstream and
ofstream classes.
Member functions : all input and output functions,
open(), close()
ifstream It provides input operations for file.
Member functions : get(), getline(), read(),
seekg(), tellg()
ofstream It provides output operations for file.
Member functions : put(), write(), seekp(), tellp()
fstream It is an input-output stream class
Opening and closing files
In C++, if we want to open a file, we must first obtain a
stream.(objects)
Opening of files can be achieved in two ways:
1. using the constructor function of the stream class
syntax : stream streamobject(“name of filename”);
2. using the function Open( )
Syntax : stream streamobject;
streamobject.open(“name of filename”);
A file is closed by disconnecting it with the stream it is
associated with.
Syntax : streamobject.close()
Types of Files
Files are of two types.
1. ASCII file or Text File :
Those files created by storing
characters
2. Binary file :
Those files created by storing a
block of memory
The concept of file modes:
It describes how a file is to be used
•to read from it
•to write to it
•to append it
•to read and write and so on.
Syntax :
streamobject.open( “filename”, file-mode);
File mode constants
Sl.No File modes Meaning
Stream
type
1 ios :: in it opens file for reading ifstream
2 ios :: out it opens file for writing ofstream
3 ios :: app
It causes all output to that file to be
appended to the end
ofstream
4 ios :: ate
It seeks to end-of-file upon opening of the
file.
ofstream
5 ios :: trunc Delete contents of the file if it exists ofstream
6 ios :: nocreate
It causes the open() functions to fail if the
file does not already exist. It will not create
a new file with that name.
ofstream
7 ios :: noreplace
It causes the open() functions to fail if the
file already exist. This is used when we
want to create a new file and at the same
time
ifstream
8 ios :: binary
It causes a file to be opened in binary
mode.
ifstream,
ofstream
Reading and writing characters
from / to disk
The functions put() and get() are used
for manipulating a file character by
character.
These functions are members of ostream
and istream respectively.
put() is used for output to the file.
get() is used for input from file.
To create a File using put()
#include<fstream.h>
void main()
{
ofstream outfile(“out.txt”);
char str[]=“This is a text file”;
int i=0;
while(str[i])
outfile.put(str[i++]);
outfile.close();
}
To read a File using get()
#include<fstream.h>
void main()
{ char ch;
ifstream infile(“out.txt”);
while(infile)
{ infile.get(ch);
cout << ch;
}
infile.close();
}
Detecting End of File(eof())
eof() is a member of ios class.
It returns a non-zero value if the end-
of-file is encountered and a zero
otherwise.
Reading and writing class objects
from / to disk
The functions write() and read() are
usually used to transfer a block of data
from and to the file.
These functions are members of
ofstream and ifstream respectively.
write() is used for output to the file.
read() is used for input from file.
write() function
To write to the file
It takes two arguments
i.e., a pointer to the block and
the size of the block
Eg.,
stdfile.write((char *)&s, sizeof(student));
read() function
To get the contents from the file
It takes two arguments
i.e., a pointer to the block and
the size of the block
Eg.,
stdfile.read((char *)&s, sizeof(student));
Program to Create a student File
#include <fstream.h>
class student
{
private :
int regno, mark;
char name[20];
public:
void getdata();
};
void student :: getdata()
{
cout << “nEnter reg. number: “;
cin >> regno;
cout << “nEnter Name of Student:”;
gets(name);
cout << “nEnter Marks:”;
cin >> marks;
}
void main()
{ student ob;
fstream stdfile;
stdfile.open(“stud.dat”,ios::out);
char flag;
do
{ ob.getdata();
stdfile.write((char *)&ob,
sizeof(student));
cout << “n Continue ? y/n”;
cin >> flag;
} while(flag==‘Y’ || flag==‘y’);
stdfile.close();
}
Program to Display a student File
#include <fstream.h>
class student
{
private :
int regno, mark;
char name[20];
public:
void getdata();
void display();
};
void student :: getdata()
{
cout << “nEnter reg. number: “;
cin >> regno;
cout << “nEnter Name of Student:”;
gets(name);
cout << “nEnter Marks:”;
cin >> marks;
}
void student :: display()
{
cout << “nRegister number: “ <<regno;
cout << “nName of Student:”<<name;
cout << “nMarks:” <<marks;
}
void main()
{ student ob;
fstream stdfile;
stdfile.open(“stud.dat”,ios::in);
stdfile.read((char *)&ob,sizeof(student));
while(stdfile)
{
ob.display();
stdfile.read((char *)&ob,sizeof(student));
}
stdfile.close();
}
Open for READING only H A I
Input pointer
Open for WRITING only
output pointer
Open for APPEND mode H A I
output pointer
File Pointers for Random Access
When we open a file in more than one mode using
the fstream class, it is not necessary to close the file
and open it again when we need to switch from one
mode to another.
But if we are writing and reading in different in
different positions of the file, then, the stream
pointers have to be positioned appropriately.
Each file object is associated with two integer values
called the get_pointer and the put_pointer. These
are also called the current postion. These values
specify the byte number in the file.
Functions to move the File Pointer
seekg() Moves get_pointer(input
pointer) to a specified location.
seekp() Moves put_pointer(output
pointer) to a specified location.
tellg() Gives the current position to the
get_pointer
tellp() Gives the current position to the
put_pointer
Example:
infile.seekg(15);
It moves the file pointer to the byte number 15.
It is to be remembered that the bytes in a file
are numbered beginning from zero. Therefore,
the file pointer will be pointing to the 16th byte
in the file
Example:
ofstream ofile;
ofile.open(“employee”,ios::app);
int ptr = ofile.tellp();
On execution of these statements, the output
pointer will be moved to the end of the file
“employee” and the value of ptr will represent
the number of bytes in the file.
seekg() and seekp() functions
 It takes one or two arguments.
 If it takes two arguments, then
the first one is the relative offset, ie., the
number of bytes the file pointer has to be moved
(+ for forward and – for backward)
The second argument is the position of the file
pointer from where the offset is to be considered.
 The default argument for this is the beg
 It can take values ios::beg, ios::end, ios::cur
Error Handling functions
The different possible error situations are
enumerated below
 The file name used for a new file may be an
existing file name
 A file which we are attempting to open for reading
may not exist.
 There may be no more room on the disk for storing
the newly created file.
 We may attempt to perform an operation when the
file is not opened for that purpose.
Error Handling Functions
eof() Returns non-zero if the end of file is
encountered while reading. Otherwise
returns zero.
fail() Returns non-zero when an input or
output operation has failed.
bad() Returns non-zero values if an invalid
operation is attempted or any
unrecoverable error has occurred.
However, if it is zero it may be possible to
recover from any other error reported
and continue operation
Error Handling Functions
good() Returns non-zero values if no error
has occurred. When it returns zero, no
further operations can be carried out.
clear() Resets the error state so that further
operations can be attempted
Ad

More Related Content

What's hot (20)

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
Kulachi Hansraj Model School Ashok Vihar
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
RAGAVIC2
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 

Viewers also liked (20)

File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
Kulachi Hansraj Model School Ashok Vihar
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
File Pointers
File PointersFile Pointers
File Pointers
Kulachi Hansraj Model School Ashok Vihar
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
Papu Kumar
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
Dr .Ahmed Tawwab
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
Online
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
archikabhatia
 
Managing console
Managing consoleManaging console
Managing console
Shiva Saxena
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Vcs26
Vcs26Vcs26
Vcs26
Malikireddy Bramhananda Reddy
 
Unit iv
Unit ivUnit iv
Unit iv
donny101
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
Anton Kolotaev
 
Linked list
Linked listLinked list
Linked list
Md. Afif Al Mamun
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
Ganesh Samarthyam
 
8 header files
8 header files8 header files
8 header files
Bint EL-maghrabi
 
Ad

Similar to Files in c++ (20)

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
anuvayalil5525
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Files in c++
Files in c++Files in c++
Files in c++
NivethaJeyaraman
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
Introduction to files management systems
Introduction to files management systemsIntroduction to files management systems
Introduction to files management systems
araba8
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
baabtra.com - No. 1 supplier of quality freshers
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
study material
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
Daniel Nyagechi
 
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
Sunil Patel
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
Filehandling
FilehandlingFilehandling
Filehandling
Muhammad Fahad
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
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
anuvayalil5525
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
sanya6900
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbbfile_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Introduction to files management systems
Introduction to files management systemsIntroduction to files management systems
Introduction to files management systems
araba8
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
study material
 
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
Sunil Patel
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Ad

More from Selvin Josy Bai Somu (8)

Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
Selvin Josy Bai Somu
 
Web technology
Web technologyWeb technology
Web technology
Selvin Josy Bai Somu
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
Selvin Josy Bai Somu
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
Selvin Josy Bai Somu
 
Inheritance
InheritanceInheritance
Inheritance
Selvin Josy Bai Somu
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Selvin Josy Bai Somu
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
Selvin Josy Bai Somu
 

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 

Files in c++

  • 1. Prepared by : SELVIN JOSY BAI.S
  • 2.  Use of header file fstream.h  Types of stream objects  open() and close() functions  File mode constants  Reading and writing characters from / to disk  Detecting end of file  Reading and writing objects from / to disk  File pointers for Random Access  Error handling functions
  • 3. Most computer programs work with files. Word processors create document files. Database programs create files of information. Compilers read source files and generate executable files. In C++, file input / output facilities are implemented through a component header file of C++ standard library. This header file is fstream.h.
  • 4. File Stream Read data A File stream act as an interface between the program and the files. •The stream that supplies data to the program is known as input stream. •The stream that receives data from the program is known as output stream. Disk Files Program Data input Write data Data output Output stream Input stream
  • 5. CLASSES FOR FILE STREAM OPERATIONS ios istream streambuf ostream iostream ifstream fstream ofstream filebuf fstreambase ……………………………………………………………………………………………………………………………………………. iostreamfilefstreamfile
  • 6. Using fstream.h A stream is a sequence of bytes. It is a general name given to a flow of data. Different streams are used to represent different kinds of data flow. ifstream class represents input disk files. ofstream class represents output disk files. fstream – for both input and output Member functions of these classes are used to perform I/O operations.
  • 7. Different Classes and its functions Class Functions filebuf It sets the file buffers to read and write. Member functions : open(), close() fstreambase This is the base class for fstream, ifstream and ofstream classes. Member functions : all input and output functions, open(), close() ifstream It provides input operations for file. Member functions : get(), getline(), read(), seekg(), tellg() ofstream It provides output operations for file. Member functions : put(), write(), seekp(), tellp() fstream It is an input-output stream class
  • 8. Opening and closing files In C++, if we want to open a file, we must first obtain a stream.(objects) Opening of files can be achieved in two ways: 1. using the constructor function of the stream class syntax : stream streamobject(“name of filename”); 2. using the function Open( ) Syntax : stream streamobject; streamobject.open(“name of filename”); A file is closed by disconnecting it with the stream it is associated with. Syntax : streamobject.close()
  • 9. Types of Files Files are of two types. 1. ASCII file or Text File : Those files created by storing characters 2. Binary file : Those files created by storing a block of memory
  • 10. The concept of file modes: It describes how a file is to be used •to read from it •to write to it •to append it •to read and write and so on. Syntax : streamobject.open( “filename”, file-mode);
  • 11. File mode constants Sl.No File modes Meaning Stream type 1 ios :: in it opens file for reading ifstream 2 ios :: out it opens file for writing ofstream 3 ios :: app It causes all output to that file to be appended to the end ofstream 4 ios :: ate It seeks to end-of-file upon opening of the file. ofstream 5 ios :: trunc Delete contents of the file if it exists ofstream 6 ios :: nocreate It causes the open() functions to fail if the file does not already exist. It will not create a new file with that name. ofstream 7 ios :: noreplace It causes the open() functions to fail if the file already exist. This is used when we want to create a new file and at the same time ifstream 8 ios :: binary It causes a file to be opened in binary mode. ifstream, ofstream
  • 12. Reading and writing characters from / to disk The functions put() and get() are used for manipulating a file character by character. These functions are members of ostream and istream respectively. put() is used for output to the file. get() is used for input from file.
  • 13. To create a File using put() #include<fstream.h> void main() { ofstream outfile(“out.txt”); char str[]=“This is a text file”; int i=0; while(str[i]) outfile.put(str[i++]); outfile.close(); }
  • 14. To read a File using get() #include<fstream.h> void main() { char ch; ifstream infile(“out.txt”); while(infile) { infile.get(ch); cout << ch; } infile.close(); }
  • 15. Detecting End of File(eof()) eof() is a member of ios class. It returns a non-zero value if the end- of-file is encountered and a zero otherwise.
  • 16. Reading and writing class objects from / to disk The functions write() and read() are usually used to transfer a block of data from and to the file. These functions are members of ofstream and ifstream respectively. write() is used for output to the file. read() is used for input from file.
  • 17. write() function To write to the file It takes two arguments i.e., a pointer to the block and the size of the block Eg., stdfile.write((char *)&s, sizeof(student));
  • 18. read() function To get the contents from the file It takes two arguments i.e., a pointer to the block and the size of the block Eg., stdfile.read((char *)&s, sizeof(student));
  • 19. Program to Create a student File #include <fstream.h> class student { private : int regno, mark; char name[20]; public: void getdata(); };
  • 20. void student :: getdata() { cout << “nEnter reg. number: “; cin >> regno; cout << “nEnter Name of Student:”; gets(name); cout << “nEnter Marks:”; cin >> marks; }
  • 21. void main() { student ob; fstream stdfile; stdfile.open(“stud.dat”,ios::out); char flag; do { ob.getdata(); stdfile.write((char *)&ob, sizeof(student)); cout << “n Continue ? y/n”; cin >> flag; } while(flag==‘Y’ || flag==‘y’); stdfile.close(); }
  • 22. Program to Display a student File #include <fstream.h> class student { private : int regno, mark; char name[20]; public: void getdata(); void display(); };
  • 23. void student :: getdata() { cout << “nEnter reg. number: “; cin >> regno; cout << “nEnter Name of Student:”; gets(name); cout << “nEnter Marks:”; cin >> marks; }
  • 24. void student :: display() { cout << “nRegister number: “ <<regno; cout << “nName of Student:”<<name; cout << “nMarks:” <<marks; }
  • 25. void main() { student ob; fstream stdfile; stdfile.open(“stud.dat”,ios::in); stdfile.read((char *)&ob,sizeof(student)); while(stdfile) { ob.display(); stdfile.read((char *)&ob,sizeof(student)); } stdfile.close(); }
  • 26. Open for READING only H A I Input pointer Open for WRITING only output pointer Open for APPEND mode H A I output pointer
  • 27. File Pointers for Random Access When we open a file in more than one mode using the fstream class, it is not necessary to close the file and open it again when we need to switch from one mode to another. But if we are writing and reading in different in different positions of the file, then, the stream pointers have to be positioned appropriately. Each file object is associated with two integer values called the get_pointer and the put_pointer. These are also called the current postion. These values specify the byte number in the file.
  • 28. Functions to move the File Pointer seekg() Moves get_pointer(input pointer) to a specified location. seekp() Moves put_pointer(output pointer) to a specified location. tellg() Gives the current position to the get_pointer tellp() Gives the current position to the put_pointer
  • 29. Example: infile.seekg(15); It moves the file pointer to the byte number 15. It is to be remembered that the bytes in a file are numbered beginning from zero. Therefore, the file pointer will be pointing to the 16th byte in the file
  • 30. Example: ofstream ofile; ofile.open(“employee”,ios::app); int ptr = ofile.tellp(); On execution of these statements, the output pointer will be moved to the end of the file “employee” and the value of ptr will represent the number of bytes in the file.
  • 31. seekg() and seekp() functions  It takes one or two arguments.  If it takes two arguments, then the first one is the relative offset, ie., the number of bytes the file pointer has to be moved (+ for forward and – for backward) The second argument is the position of the file pointer from where the offset is to be considered.  The default argument for this is the beg  It can take values ios::beg, ios::end, ios::cur
  • 32. Error Handling functions The different possible error situations are enumerated below  The file name used for a new file may be an existing file name  A file which we are attempting to open for reading may not exist.  There may be no more room on the disk for storing the newly created file.  We may attempt to perform an operation when the file is not opened for that purpose.
  • 33. Error Handling Functions eof() Returns non-zero if the end of file is encountered while reading. Otherwise returns zero. fail() Returns non-zero when an input or output operation has failed. bad() Returns non-zero values if an invalid operation is attempted or any unrecoverable error has occurred. However, if it is zero it may be possible to recover from any other error reported and continue operation
  • 34. Error Handling Functions good() Returns non-zero values if no error has occurred. When it returns zero, no further operations can be carried out. clear() Resets the error state so that further operations can be attempted