Upload
amitpagal1995
View
221
Download
0
Embed Size (px)
Citation preview
7/28/2019 141303 Random Access 5THUNIT 2
1/30
Data File HandlingData File Handlingin C++in C++
Guided by:Guided by:
N RakheshN RakheshPGT (Comp. Science)PGT (Comp. Science)
Kendriya Vidyalaya Railway ColonyKendriya Vidyalaya Railway Colony
BangaloreBangalore
A
A
A
A
A
A
7/28/2019 141303 Random Access 5THUNIT 2
2/30
All rights reserved 2
Topics - AgendaTopics - Agenda IntroductionIntroduction
Opening & closing of filesOpening & closing of files
Stream state member functionsStream state member functions
File operationsFile operations
Binary file operationsBinary file operations
Random access file operationsRandom access file operations
CBSE Question Pattern from this topicCBSE Question Pattern from this topic ConclusionConclusion
7/28/2019 141303 Random Access 5THUNIT 2
3/30
All rights reserved 3
Introduction 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 acomponent header file calledfstream.hfstream.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 certainclasses.
7/28/2019 141303 Random Access 5THUNIT 2
4/30
TheThe fstream.h
fstream.hheader fileheader file
Streams act as an interface between files andStreams act as an interface between files andprograms.programs.
They represent as a sequence of bytes and deals withThey represent as a sequence of bytes and deals withthe flow of data.the flow of data.
Every stream is associated with a class having memberEvery stream is associated with a class having memberfunctions and operations for a particular kind of datafunctions and operations for a particular kind of data
flow.flow.
FileFile Program ( Input stream) - readsProgram ( Input stream) - readsProgramProgram File (Output stream) writeFile (Output stream) write
All designed into fstream.h and hence needs to beAll designed into fstream.h and hence needs to beincluded in all file handling programs.included in all file handling programs.
Diagrammatically as shown in next slideDiagrammatically as shown in next slide
7/28/2019 141303 Random Access 5THUNIT 2
5/30
All rights reserved 5
7/28/2019 141303 Random Access 5THUNIT 2
6/30
File Handling ClassesHierarchy Diagram
7/28/2019 141303 Random Access 5THUNIT 2
7/30
Why to use Files:Why to use Files:
Convenient way to deal large quantities of data.Convenient way to deal large quantities of data.
Store data permanently (until file is deleted).Store data permanently (until file is deleted).
Avoid typing data into program multiple times.Avoid typing data into program multiple times.Share data between programs.Share data between programs.
We need to know:We need to know:
how to "connect" file to programhow to "connect" file to programhow to tell the program to read datahow to tell the program to read data
how to tell the program to write datahow to tell the program to write data
error checking and handling EOFerror checking and handling EOF
7/28/2019 141303 Random Access 5THUNIT 2
8/30
All rights reserved 9
// Initial experience reading and writing files#include #include #include int main(){ ifstream in_stream;ofstream out_stream;int num;
in_stream.open("numbers.dat");if (in_stream.fail()) { cout
7/28/2019 141303 Random Access 5THUNIT 2
9/30
File Handling Classes When working with files in C++, the followingWhen working with files in C++, the following
classes can be used:classes can be used: ofstream writing to a file ifstream reading for a file
fstream reading / writing
What does it all have to do with cout?What does it all have to do with cout? When ever we include , an ostreamobject, pointing to stdout is automatically defined this object is cout.
ofstream inherits from the class ostream
(standard output class). ostream overloaded the operator >> for standard
output.thus an ofstream object canuse methods and operators defined inostream.
7/28/2019 141303 Random Access 5THUNIT 2
10/30
Opening & Closing a FileOpening & Closing a File A file can be open by the method open() orA file can be open by the method open() or
immediately in the constructor (theimmediately in the constructor (the naturalnatural andand
preferred way).preferred way).void ofstream / ifstream::open(const char* filename, int mode);void ofstream / ifstream::open(const char* filename, int mode);
filename file to open (full path or local)filename file to open (full path or local)mode how to open (1 or more of following using | )mode how to open (1 or more of following using | )
ios::app appendios::app appendios::ate open with marker at the end of the fileios::ate open with marker at the end of the fileios::in / ios::out (the defaults of ifstream andios::in / ios::out (the defaults of ifstream and
ofstream)ofstream)ios:nocreate / ios::noreplace open only if the fileios:nocreate / ios::noreplace open only if the file
exists / doesnt existexists / doesnt exist
ios::trunc open an empty fileios::trunc open an empty fileios::binary open a binary file (default is textual)ios::binary open a binary file (default is textual)
Dont forget to close the file using the methodDont forget to close the file using the methodclose()close()
7/28/2019 141303 Random Access 5THUNIT 2
11/30
All rights reserved 12
1: To access file handling routines:
#include #include
2: To declare variables that can be used to access file:
ifstream in_stream;ifstream in_stream;ofstream out_stream;ofstream out_stream;
3: To connect your program's variable (its internal name) to
an external file (i.e., on the Unix file system):
in_stream.open("infile.dat");in_stream.open("infile.dat");out_stream.open("outfile.dat");out_stream.open("outfile.dat");
4: To see if the file opened successfully:
if (in_stream.fail())if (in_stream.fail())
{ cout
7/28/2019 141303 Random Access 5THUNIT 2
12/30
7/28/2019 141303 Random Access 5THUNIT 2
13/30
Stream state member functionsStream state member functions
In C++, file stream classes inherit a stream stateIn C++, file stream classes inherit a stream state
member from the ios class, which gives out themember from the ios class, which gives out the
information regarding the status of the stream.information regarding the status of the stream.
For e.g.:For e.g.:
eof() used to check the end of file charactereof() used to check the end of file character
fail()- used to check the status of file at openingfail()- used to check the status of file at opening
for I/Ofor I/Obad()- used to check whether invalid filebad()- used to check whether invalid file
operations or unrecoverable error .operations or unrecoverable error .
good()- used to check whether the previous filegood()- used to check whether the previous file
operation has been successfuloperation has been successful
7/28/2019 141303 Random Access 5THUNIT 2
14/30
File operationsFile operations
The following member functions are usedThe following member functions are usedfor reading and writing a character from afor reading and writing a character from a
specified file.specified file.get()- is used to read an alphanumericget()- is used to read an alphanumericcharacter from a file.character from a file.
put()- is used to write a character to aput()- is used to write a character to aspecified file or a specified output streamspecified file or a specified output stream
R di /W iti f /t
7/28/2019 141303 Random Access 5THUNIT 2
15/30
Reading /Writing from/toBinary Files
To write n bytes: write (const unsigned char* buffer, int n); To read n bytes (to a pre-allocated buffer):
read (unsighed char* buffer, int num)
#include main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.txt, ios::out |ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}
C ARAC R OCHARACTER I/O
7/28/2019 141303 Random Access 5THUNIT 2
16/30
All rights reserved 17
C++ has some low-level facilities for character I/O.C++ has some low-level facilities for character I/O.
char next1, next2, next3;char next1, next2, next3;
cin.get(next1);cin.get(next1);Gets the next character from the keyboard. Does not skip overGets the next character from the keyboard. Does not skip over
blanks or newline (\n). Can check for newline (next == '\n')blanks or newline (\n). Can check for newline (next == '\n')
Example:Example:
cin.get(next1);cin.get(next1);cin.get(next2);cin.get(next2);
cin.get(next3);cin.get(next3);
Predefined character functions must #include and can be
used to
convert between upper and lower casetest whether in upper or lower casetest whether alphabetic character or digittest for space
CHARACTER I/OCHARACTER I/O
//#i l d t t id i () itt d f
7/28/2019 141303 Random Access 5THUNIT 2
17/30
All rights reserved 18
//#include, prototypes, void main() omitted for space
ifstream fin;
char Chem1, Chem2;
double ratio;
fin.open("input.dat"); // open error check omitted for space
fin.get(Chem1);
while (!fin.eof()){
if (isdigit(Chem1))
cout
7/28/2019 141303 Random Access 5THUNIT 2
18/30
Reading /Writing from/to Textual FilesReading /Writing from/to Textual Files
To write: put() writing single
character > operator reading a object
#include main()
{// Writing to fileofstream OutFile("my_file.txt");OutFile
7/28/2019 141303 Random Access 5THUNIT 2
19/30
All rights reserved 20
Binary file operationsBinary file operationsIn connection with a binary file, the file
mode must contain the ios::binary modealong with other mode(s)
To read & write a or on to a binaryfile, as the case may be blocks ofdata are accessed through the useof C++ read() and write()
respectively.
7/28/2019 141303 Random Access 5THUNIT 2
20/30
All rights reserved 21
Random access fileRandom access file
operationsoperationsEvery file maintains two internal pointers:Every file maintains two internal pointers:
get_pointer and put_pointerget_pointer and put_pointer
They enable to attain the random access in fileThey enable to attain the random access in fileotherwise which is sequential in nature.otherwise which is sequential in nature.
In C++ randomness is achieved by manipulatingIn C++ randomness is achieved by manipulatingcertain functionscertain functions
7/28/2019 141303 Random Access 5THUNIT 2
21/30
Moving within the File
seekg() / seekp() moving the reading(get) / writing (put) marker two parameters: offset and anchor
tellg() / tellp() getting the positionof the reading (get) / writing (put)
marker
7/28/2019 141303 Random Access 5THUNIT 2
22/30
All rights reserved 23
EOF and File I/O Within FunctionsEOF and File I/O Within FunctionsWhen using a file within a function, the file parameter
MUST BE a reference parameter:
int read_file(ifstream& infile);As with keyboard input, it is often desirable to processAs with keyboard input, it is often desirable to process
some unknown amount of data. We use the end-of-filesome unknown amount of data. We use the end-of-file
(EOF) to accomplish this. EOF is automatically included(EOF) to accomplish this. EOF is automatically included
in text files we create.in text files we create.
Can test for EOF in several ways.Can test for EOF in several ways.while (in_stream >> num)while (in_stream >> num)
OROR
in_stream >> num; // priming readin_stream >> num; // priming readwhile (! in_stream.eof())while (! in_stream.eof())
{loop body{loop body
in_stream >> num;}in_stream >> num;}
7/28/2019 141303 Random Access 5THUNIT 2
23/30
All rights reserved 24
int main()
{
ofstream out_stream;
double d1, d2;
char file_name[20]; // cstringcout > file_name;
out_stream.open(file_name);
if (out_stream.fail())
{cout d1 >> d2;
out_stream
7/28/2019 141303 Random Access 5THUNIT 2
24/30
All rights reserved 25
int main()
{
int side1, side2, side3, perimeter;
double area;
ifstream in_stream;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
open_input_file(in_stream);
cout
7/28/2019 141303 Random Access 5THUNIT 2
25/30
All rights reserved 26
void open_input_file(ifstream& instream)
{ instream.open("lengths.dat");
if (instream.fail())
{ cout
7/28/2019 141303 Random Access 5THUNIT 2
26/30
CBSE QUESTION PATTERNCBSE QUESTION PATTERNRELATEDRELATED
TOTO
DATA FILE HANDLINGDATA FILE HANDLING
7/28/2019 141303 Random Access 5THUNIT 2
27/30
All rights reserved 28
Summary Files in C++ are interpreted as a sequence of
bytes stored on some storage media. Bases classes are used to perform I/O
operations.
The data of a file is stored in eitherreadable form or in binary code called astext file or binary file.
The flow of data from any source to a sinkis called as a stream.
More Information on File I/OMore Information on File I/O
7/28/2019 141303 Random Access 5THUNIT 2
28/30
All rights reserved 29
1. When getting data from a file, there is no need to prompt for input.
2. One program may have multiple input and/or output files, and may
intermix keyboard/ display I/O with file I/O.
3. The file name may be obtained from the user, rather than hard coded inthe program.
4. The layout of a program's output is called the format. A variety of
options are available for controlling the appearance of the output.
5. Flags to control floating point display:
out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);
6. rd_state() returns a variable with one or more (check with AND) of the
following options: ios::goodbit OK ios::eofbit marker on EOF ios::failbit illegal action, but alright to continue ios:badbit corrupted file, cannot be used.
7. We can also access the bit we wish to check with eof(), good(), fail(),
bad(),
8. clear() is used to clear the status bits (after they were checked).
More Information on File I/OMore Information on File I/O
7/28/2019 141303 Random Access 5THUNIT 2
29/30
All rights reserved 30
Questions ? ?
7/28/2019 141303 Random Access 5THUNIT 2
30/30
Presented by:Presented by:
N RAKHESHN RAKHESH
PGT Comp. SciencePGT Comp. Science
KVSKVS