SlideShare a Scribd company logo
FILE HANDLING IN C++
Introduction
 All programs we looked earlier:
 input data from the keyboard.
 output data to the screen.
 Difficult to handle large amount of input data.
 Output would also be lost as soon as we exit

from the program.
 How do we store data permanently?.
 We can use secondary storage device.
 Data is packaged up on the storage device as data
structures called files.
Files (Streams)
 Files

are used to store data in a relatively
permanent form, on floppy disk, hard disk,
tape or other form of secondary storage.
Files can hold huge amounts of data if
need be. Ordinary variables (even records
and arrays) are kept in main memory
which is temporary and rather limited in
size.
Lets put it in points…………..
Why use files?
Convenient way to deal with large
quantities of data.
• Store data permanently (until file is
deleted).
• Avoid having to type data into
program multiple times.
• Share data between programs.
•
The following is a
comparison
of
the two types of storage………..
Main memory

•

Made up of RAM chips.

•

Used to hold a program
when it is running,
including the values of its
variables
(whether
integer, char, an array,
etc.)

Secondary memory

•

Usually a disk
magnetic tape).

drive

(or

•

Used to hold files (where a file
can contain data, a program,
text, etc.)

•

Can hold rather large amounts
of data.
Main memory

Secondary memory

•

Can only hold relatively
small amounts of data.

•

Can hold rather
amounts of data.

•

Is temporary (as soon
as the program is done
or the power goes out
all of these values are
gone).

•

•

Gives fast access to
the data (all electronic).

Is fairly permanent. (A file
remains even if the power
goes out. It will last until
you erase it, as long as
the disk isn't damaged, at
least.)

 Access

large

to the data is
considerably slower (due
to moving parts).
I/O in C++
 I/O

in C++ uses streams
 A Stream is a general name given to
flow of data.
Flow of Data….

PROGRAM
Input
Stream
>>
(Extraction
operator)
istream class

DEVICES OR
Data

FILES

Data

Output
Stream
<<
(Insertion
operator)
ostream class
More About Files…..
 Now

we need to know:

 how

to "connect" file to program
 how to tell the program to read data
 how to tell the program to write data
 error checking and handling eof
I/O in C++
 Different

streams are used to represent
different kinds of data flow.

 Each

stream is associated with a
particular class, which contains
member functions and
 definitions for dealing with that particular
kind of data flow.

File Related Classes
The following classes in C++
have access to file input and
output functions:
 ifstream
 ofstream
 fstream
The Stream Class Hierarchy
ios

NOTE : UPWARD ARROWS INDICATE
THE BASE CLASS

istream
get()
getline()
read()
>>

fstreambase

Ifstream
Open()
Tellg()
Seekg()

fstream

iostream

ostream
put()
write()
<<

Ofstream
Open()
Tellp()
Seekp()
OPENING A FILE
(Associating a stream with a file)

1. By using the CONSTRUCTOR of the
stream class.
ifstream transaction(“sales.dly”);
ofstream result(“result.02”);
2. By using the open() function of the
stream class
ifstream transaction;
transaction.open(“sales.dly”);
File Mode Parameters
PARAMETER
 ios::app
 ios::ate
 ios::binary
 ios::in
 ios::nocreate
 ios::noreplace
 ios::out
 ios::trunc

MEANING
Append to end-of file
goto end of file on opening
binary file
Open existing file for reading
open fails if file doesn’t exist
open fails if file already exists
creates new file for writing on
Deletes contents if it exists

The mode can combine two or more modes using bit wise or ( | )
Checking For Successful File
Opening
ifstream transaction(“sales.dly”);
if (transcation == NULL)
{
cout<<“unable to open sales.dly”;
cin.get(); // waits for the operator to press any key
exit(1);
}
Closing of File
Stream_name.close();
e.g., transaction.close();
fl.close();

Note : There is no need to give the physical
file name at the time of closing a file.
Types of Files
 The

two basic types of files are

 Text

files

&
 Binary

files
Text Files
A

text file consists of readable characters
separated into lines by newline
characters.

 (On

most PCs, the newline character is
actually represented by the two-character
sequence of carriage return (ASCII 13),
line feed (ASCII 10). (n)
Binary Files
A

binary file stores data to disk in the
same form in which it is represented in
main memory.



If you ever try to edit a binary file
containing numbers you will see that the
numbers
appear
as
nonsense
characters.
Binary Files
 Not

having to translate numbers into a
readable form makes binary files
somewhat more efficient.

 Binary

files also do not normally use
anything to separate the data into
lines.

 Such

a file is just a stream of data with
nothing in particular to separate
components.
Text Files
When using a text
file, we write out
separately each of
the pieces of data
about a given
record.
The text file will be
readable by an
editor

Binary Files
 When

using a
binary file we write
whole record data
to the file at once.

 but

the numbers in
the binary file will
not be readable in
this way.
The programs to create the data files will differ in how they
open the file and in how they write to the file.


for the text file we will
use the usual output
operator(<<) and will
output each of the
pieces of the record
separately.

 For the binary file we
will use write to write to
the file,



with the text file we will
read each of the pieces
of record from the file
separately, using the
usual input operator(>>)

 With the binary file we
will use the read
function to read a
whole record,
Types

of File Access

:Sequential access. With this type of file
access one must read the data in order,
much like with a tape, whether the data is
really stored on tape or not.
Random access (or direct access). This
type of file access lets you jump to any
location in the file, then to any other, etc.,
all in a reasonable amount of time.
FILE POINTERS
FILE POINTERS
 Each

file object has two integer values
associated with it :
 get

pointer
 put pointer
 These

values specify the byte number
in the file where reading or writing will
take place.
File pointers…..
 By

default reading pointer is set at the
beginning.
 By default writing pointer is set at the
end (when you open file in ios::app
mode)
 There are times when you must take
control of the file pointers yourself so
that you can read from and write to an
arbitrary location in the file.
Functions associated with file
pointers :
 The

seekg() and tellg() functions allow
you to set and examine the get pointer.

 The

seekp() and tellp() functions allow
you to set and examine the put pointer.
seekg() function : (with one argument)
 With

one argument :
fl.seekg(k);
fl.seekp(k);

where k is absolute position from the beginning. The
start of the file is byte 0
It will result in moving the pointer as shownFile

Begin
k bytes

^
File pointer

End
‘seek’ functions : (With two arguments )
fl.seekg(offset, refposition);
fl.seekp(offset, refposition);
Number of bytes file
pointer to be moved

Location from where File
pointer is to be moved

Refposition takes one of the following forms :
•ios::beg Start of the file
•ios::cur current position of the pointer
•ios::end End of the file
File Pointer offset calls
•fl.seekg(0,ios::beg); Go to start
•fl.seekg(0,ios::cur); Stay at the current position
•fl.seekg(0,ios::end); Go to the end of file
•fl.seekg(m,ios::beg);Move to (m+1)th byte in the file
File Pointer offset calls
•fl.seekg(m,ios::cur);

Go forward by m bytes
from current pos

•fl.seekg(-m,ios::beg);

Go backward by m bytes
from current pos

•fl.seekg(-m,ios::cur);

Go backward by m bytes
from the end
seekg() function : (With two arguments )
:
Begin

End

•fl.seekg(m,ios::beg);
m bytes

^
Offset from Begin

Move to (m+1)th byte in the file
End

Begin

fl.seekg(-m,ios::cur);
Offset from end

^

m bytes

Go backward by m bytes from the end
End

Begin

fl.seekg(m,ios::cur);
m bytes

^

Offset from current
position

Go forward by m bytes from current pos
EXAMPLES


Creation of a text file
Program to generate coded file……
(Text File)
#include <fstream.h>
#include <conio.h>
#include <stdio.h>
void main()
{ clrscr();
char c,d,ans;
char str[80];
ofstream outfl("try.txt");
do
{ cout<<"please give the string : ";
gets(str);
outfl<<str;
cout <<"do you want to write more...<y/n> : ";
ans=getch();
} while(ans=='y');
outfl<<'0';
outfl.close();

clrscr();

ifstream infl;
getch();
cout <<"reading from created file n";
infl.open("try.txt");
out.open("cod.dat");
//**********************************
c=infl.get();
do
{ d=c+1;
cout<<c<<d<<'n';
out.put(d);
c= infl.get();
} while (c!='0');
out<<'0';
infl.close();
outfl.close();
getch();
//*********************************
}
The End

More Related Content

PPT
File handling in_c
PDF
Filehadnling
PPTX
Data file handling in c++
PPT
File handling in C++
PPSX
Files in c++
File handling in_c
Filehadnling
Data file handling in c++
File handling in C++
Files in c++

What's hot (20)

PPT
working file handling in cpp overview
DOCX
File handling in c++
PPT
File Handling In C++(OOPs))
PPTX
File handling in c++
PPT
Cpp file-handling
PDF
C++ Files and Streams
PPTX
basics of file handling
PPT
Files in c++ ppt
PPTX
Data file handling
PPT
17 files and streams
PPT
File in cpp 2016
PPTX
Pf cs102 programming-8 [file handling] (1)
PDF
08. handling file streams
PPTX
Files in c++
PPTX
Stream classes in C++
PDF
file handling c++
PPTX
Filesin c++
PPT
File handling
PDF
Files and streams
working file handling in cpp overview
File handling in c++
File Handling In C++(OOPs))
File handling in c++
Cpp file-handling
C++ Files and Streams
basics of file handling
Files in c++ ppt
Data file handling
17 files and streams
File in cpp 2016
Pf cs102 programming-8 [file handling] (1)
08. handling file streams
Files in c++
Stream classes in C++
file handling c++
Filesin c++
File handling
Files and streams
Ad

Viewers also liked (15)

PPT
Command line arguments.21
PDF
8 header files
PDF
A COMPLETE FILE FOR C++
DOCX
C++ file
DOCX
Type header file in c++ and its function
DOC
Practical Class 12th (c++programs+sql queries and output)
PPT
PPT
Dijksatra
PPT
Disk scheduling algorithms
PPTX
Disk scheduling
PPT
4.4 external hashing
PPT
9 cm402.18
POT
Arrays and addressing modes
PPT
Minimum spanning tree
PPTX
Implicit objects advance Java
Command line arguments.21
8 header files
A COMPLETE FILE FOR C++
C++ file
Type header file in c++ and its function
Practical Class 12th (c++programs+sql queries and output)
Dijksatra
Disk scheduling algorithms
Disk scheduling
4.4 external hashing
9 cm402.18
Arrays and addressing modes
Minimum spanning tree
Implicit objects advance Java
Ad

Similar to Filehandlinging cp2 (20)

PDF
Filepointers1 1215104829397318-9
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
PPT
file_handling_in_c.ppt......................................
PPT
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
PPTX
Basics of file handling
PDF
Basics of files and its functions with example
PPTX
File Handling
PPTX
File management in C++
PDF
Files in C++.pdf is the notes of cpp for reference
PDF
Data file handling
PPTX
Working with files in c++. file handling
PPTX
working with files
PPTX
Chapter4.pptx
PPT
7 Data File Handling
PPTX
File Management and manipulation in C++ Programming
PPTX
Reading and Writing Files
PDF
Filesinc 130512002619-phpapp01
PDF
file_c.pdf
PPT
Data file handling
PPTX
Introduction to files management systems
Filepointers1 1215104829397318-9
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
file_handling_in_c.ppt......................................
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
Basics of file handling
Basics of files and its functions with example
File Handling
File management in C++
Files in C++.pdf is the notes of cpp for reference
Data file handling
Working with files in c++. file handling
working with files
Chapter4.pptx
7 Data File Handling
File Management and manipulation in C++ Programming
Reading and Writing Files
Filesinc 130512002619-phpapp01
file_c.pdf
Data file handling
Introduction to files management systems

Recently uploaded (20)

PPTX
Job-opportunities lecture about it skills
PPTX
ESD MODULE-5hdbdhbdbdbdbbdbdbbdndbdbdbdbbdbd
PPT
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
PPTX
The Stock at arrangement the stock and product.pptx
PDF
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
PPTX
PMP (Project Management Professional) course prepares individuals
PDF
Manager Resume for R, CL & Applying Online.pdf
PDF
Blue-Modern-Elegant-Presentation (1).pdf
PDF
esg-supply-chain-webinar-nov2018hkhkkh.pdf
PPTX
Your Guide to a Winning Interview Aug 2025.
PPTX
Discovering the LMA Course by Tim Han.pptx
PPTX
chapter 3_bem.pptxKLJLKJLKJLKJKJKLJKJKJKHJH
PPTX
Overview Planner of Soft Skills in a single ppt
PPTX
Principles of Inheritance and variation class 12.pptx
PDF
MCQ Practice CBT OL Official Language 1.pptx.pdf
PPTX
退学买新西兰毕业证(WelTec毕业证书)惠灵顿理工学院毕业证国外证书制作
PDF
Josh Gao Strength to Strength Book Summary
DOCX
mcsp232projectguidelinesjan2023 (1).docx
PPTX
1751884730-Visual Basic -Unitj CS B.pptx
PDF
Sales and Distribution Managemnjnfijient.pdf
Job-opportunities lecture about it skills
ESD MODULE-5hdbdhbdbdbdbbdbdbbdndbdbdbdbbdbd
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
The Stock at arrangement the stock and product.pptx
Daisia Frank: Strategy-Driven Real Estate with Heart.pdf
PMP (Project Management Professional) course prepares individuals
Manager Resume for R, CL & Applying Online.pdf
Blue-Modern-Elegant-Presentation (1).pdf
esg-supply-chain-webinar-nov2018hkhkkh.pdf
Your Guide to a Winning Interview Aug 2025.
Discovering the LMA Course by Tim Han.pptx
chapter 3_bem.pptxKLJLKJLKJLKJKJKLJKJKJKHJH
Overview Planner of Soft Skills in a single ppt
Principles of Inheritance and variation class 12.pptx
MCQ Practice CBT OL Official Language 1.pptx.pdf
退学买新西兰毕业证(WelTec毕业证书)惠灵顿理工学院毕业证国外证书制作
Josh Gao Strength to Strength Book Summary
mcsp232projectguidelinesjan2023 (1).docx
1751884730-Visual Basic -Unitj CS B.pptx
Sales and Distribution Managemnjnfijient.pdf

Filehandlinging cp2

  • 2. Introduction  All programs we looked earlier:  input data from the keyboard.  output data to the screen.  Difficult to handle large amount of input data.  Output would also be lost as soon as we exit from the program.  How do we store data permanently?.  We can use secondary storage device.  Data is packaged up on the storage device as data structures called files.
  • 3. Files (Streams)  Files are used to store data in a relatively permanent form, on floppy disk, hard disk, tape or other form of secondary storage. Files can hold huge amounts of data if need be. Ordinary variables (even records and arrays) are kept in main memory which is temporary and rather limited in size. Lets put it in points…………..
  • 4. Why use files? Convenient way to deal with large quantities of data. • Store data permanently (until file is deleted). • Avoid having to type data into program multiple times. • Share data between programs. •
  • 5. The following is a comparison of the two types of storage………..
  • 6. Main memory • Made up of RAM chips. • Used to hold a program when it is running, including the values of its variables (whether integer, char, an array, etc.) Secondary memory • Usually a disk magnetic tape). drive (or • Used to hold files (where a file can contain data, a program, text, etc.) • Can hold rather large amounts of data.
  • 7. Main memory Secondary memory • Can only hold relatively small amounts of data. • Can hold rather amounts of data. • Is temporary (as soon as the program is done or the power goes out all of these values are gone). • • Gives fast access to the data (all electronic). Is fairly permanent. (A file remains even if the power goes out. It will last until you erase it, as long as the disk isn't damaged, at least.)  Access large to the data is considerably slower (due to moving parts).
  • 8. I/O in C++  I/O in C++ uses streams  A Stream is a general name given to flow of data.
  • 9. Flow of Data…. PROGRAM Input Stream >> (Extraction operator) istream class DEVICES OR Data FILES Data Output Stream << (Insertion operator) ostream class
  • 10. More About Files…..  Now we need to know:  how to "connect" file to program  how to tell the program to read data  how to tell the program to write data  error checking and handling eof
  • 11. I/O in C++  Different streams are used to represent different kinds of data flow.  Each stream is associated with a particular class, which contains member functions and  definitions for dealing with that particular kind of data flow. 
  • 12. File Related Classes The following classes in C++ have access to file input and output functions:  ifstream  ofstream  fstream
  • 13. The Stream Class Hierarchy ios NOTE : UPWARD ARROWS INDICATE THE BASE CLASS istream get() getline() read() >> fstreambase Ifstream Open() Tellg() Seekg() fstream iostream ostream put() write() << Ofstream Open() Tellp() Seekp()
  • 14. OPENING A FILE (Associating a stream with a file) 1. By using the CONSTRUCTOR of the stream class. ifstream transaction(“sales.dly”); ofstream result(“result.02”); 2. By using the open() function of the stream class ifstream transaction; transaction.open(“sales.dly”);
  • 15. File Mode Parameters PARAMETER  ios::app  ios::ate  ios::binary  ios::in  ios::nocreate  ios::noreplace  ios::out  ios::trunc MEANING Append to end-of file goto end of file on opening binary file Open existing file for reading open fails if file doesn’t exist open fails if file already exists creates new file for writing on Deletes contents if it exists The mode can combine two or more modes using bit wise or ( | )
  • 16. Checking For Successful File Opening ifstream transaction(“sales.dly”); if (transcation == NULL) { cout<<“unable to open sales.dly”; cin.get(); // waits for the operator to press any key exit(1); }
  • 17. Closing of File Stream_name.close(); e.g., transaction.close(); fl.close(); Note : There is no need to give the physical file name at the time of closing a file.
  • 18. Types of Files  The two basic types of files are  Text files &  Binary files
  • 19. Text Files A text file consists of readable characters separated into lines by newline characters.  (On most PCs, the newline character is actually represented by the two-character sequence of carriage return (ASCII 13), line feed (ASCII 10). (n)
  • 20. Binary Files A binary file stores data to disk in the same form in which it is represented in main memory.  If you ever try to edit a binary file containing numbers you will see that the numbers appear as nonsense characters.
  • 21. Binary Files  Not having to translate numbers into a readable form makes binary files somewhat more efficient.  Binary files also do not normally use anything to separate the data into lines.  Such a file is just a stream of data with nothing in particular to separate components.
  • 22. Text Files When using a text file, we write out separately each of the pieces of data about a given record. The text file will be readable by an editor Binary Files  When using a binary file we write whole record data to the file at once.  but the numbers in the binary file will not be readable in this way.
  • 23. The programs to create the data files will differ in how they open the file and in how they write to the file.  for the text file we will use the usual output operator(<<) and will output each of the pieces of the record separately.  For the binary file we will use write to write to the file,  with the text file we will read each of the pieces of record from the file separately, using the usual input operator(>>)  With the binary file we will use the read function to read a whole record,
  • 24. Types of File Access :Sequential access. With this type of file access one must read the data in order, much like with a tape, whether the data is really stored on tape or not. Random access (or direct access). This type of file access lets you jump to any location in the file, then to any other, etc., all in a reasonable amount of time.
  • 26. FILE POINTERS  Each file object has two integer values associated with it :  get pointer  put pointer  These values specify the byte number in the file where reading or writing will take place.
  • 27. File pointers…..  By default reading pointer is set at the beginning.  By default writing pointer is set at the end (when you open file in ios::app mode)  There are times when you must take control of the file pointers yourself so that you can read from and write to an arbitrary location in the file.
  • 28. Functions associated with file pointers :  The seekg() and tellg() functions allow you to set and examine the get pointer.  The seekp() and tellp() functions allow you to set and examine the put pointer.
  • 29. seekg() function : (with one argument)  With one argument : fl.seekg(k); fl.seekp(k); where k is absolute position from the beginning. The start of the file is byte 0 It will result in moving the pointer as shownFile Begin k bytes ^ File pointer End
  • 30. ‘seek’ functions : (With two arguments ) fl.seekg(offset, refposition); fl.seekp(offset, refposition); Number of bytes file pointer to be moved Location from where File pointer is to be moved Refposition takes one of the following forms : •ios::beg Start of the file •ios::cur current position of the pointer •ios::end End of the file
  • 31. File Pointer offset calls •fl.seekg(0,ios::beg); Go to start •fl.seekg(0,ios::cur); Stay at the current position •fl.seekg(0,ios::end); Go to the end of file •fl.seekg(m,ios::beg);Move to (m+1)th byte in the file
  • 32. File Pointer offset calls •fl.seekg(m,ios::cur); Go forward by m bytes from current pos •fl.seekg(-m,ios::beg); Go backward by m bytes from current pos •fl.seekg(-m,ios::cur); Go backward by m bytes from the end
  • 33. seekg() function : (With two arguments ) : Begin End •fl.seekg(m,ios::beg); m bytes ^ Offset from Begin Move to (m+1)th byte in the file End Begin fl.seekg(-m,ios::cur); Offset from end ^ m bytes Go backward by m bytes from the end End Begin fl.seekg(m,ios::cur); m bytes ^ Offset from current position Go forward by m bytes from current pos
  • 35. Program to generate coded file…… (Text File) #include <fstream.h> #include <conio.h> #include <stdio.h> void main() { clrscr(); char c,d,ans; char str[80]; ofstream outfl("try.txt"); do { cout<<"please give the string : "; gets(str); outfl<<str; cout <<"do you want to write more...<y/n> : "; ans=getch(); } while(ans=='y'); outfl<<'0'; outfl.close(); clrscr(); ifstream infl; getch(); cout <<"reading from created file n"; infl.open("try.txt"); out.open("cod.dat"); //********************************** c=infl.get(); do { d=c+1; cout<<c<<d<<'n'; out.put(d); c= infl.get(); } while (c!='0'); out<<'0'; infl.close(); outfl.close(); getch(); //********************************* }