27
Data File Handling Data File Handling in C++ in C++ A A A A A A A A A A A A

File Handling in C++

Embed Size (px)

Citation preview

Data File Handling Data File Handling in C++in C++

AA

AA

AA

AA

AA

AA

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 CBSE Question Pattern from this topictopic

• ConclusionConclusion

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 a component header file called fstream.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 certain classes.

The The fstream.hfstream.h header fileheader fileStreams act as an interface between files Streams act as an interface between files and programs.and programs.They represent as a sequence of bytes and They represent as a sequence of bytes and deals with the flow of data.deals with the flow of data.Every stream is associated with a class Every stream is associated with a class having member functions and operations for a having member functions and operations for a particular kind of data flow.particular kind of data flow.

File File Program ( Input stream) - reads Program ( Input stream) - readsProgram Program File (Output stream) – write File (Output stream) – write

All designed into fstream.h and hence needs All designed into fstream.h and hence needs to be included in all file handling to be included in all file handling programs.programs.Diagrammatically as shown in next slideDiagrammatically as shown in next slide

All rights reserved 5

File Handling ClassesHierarchy Diagram

Why to use Files:Why to use Files:

•Convenient way to deal large quantities Convenient way to deal large quantities of data.of data.

•Store data permanently (until file is Store data permanently (until file is deleted).deleted).

•Avoid typing data into program multiple Avoid typing data into program multiple times.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 datahow to tell the program to write datahow to tell the program to write data

error checking and handling EOFerror checking and handling EOF

All rights reserved 9

// Initial experience reading and writing files#include <fstream.h>#include <iostream.h>#include <stdlib.h>int main(){ ifstream in_stream; ofstream out_stream; int num; in_stream.open("numbers.dat"); if (in_stream.fail()) { cout << "Input file could not be opened.\n";

exit(1); } out_stream.open("squares.dat"); if (out_stream.fail()) { cout <<"Output file could not opened.\n";

exit(1); } in_stream >> num; out_stream << "The square of " << num << " is " <<num * num; in_stream.close(); out_stream.close();}

File Handling Classes• When working with files in C++, the When working with files in C++, the following classes can be used:following 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 What does it all have to do with cout?cout?– When ever we include <iostream.h>, an ostream object, 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 can use methods and operators defined in

ostream.

Opening & Closing a FileOpening & Closing a File A file can be open by the method “open()” A file can be open by the method “open()” or immediately in the constructor (the or immediately in the constructor (the naturalnatural and preferred way). and preferred way).

void ofstream / ifstream::open(const char* void ofstream / ifstream::open(const char* filename, int mode);filename, int mode);

filename – file to open (full path or filename – file to open (full path or local)local)

mode – how to open (1 or more of following mode – how to open (1 or more of following – using | )– using | )

ios::app – appendios::app – appendios::ate – open with marker at the end of ios::ate – open with marker at the end of the filethe file

ios::in / ios::out – (the defaults of ios::in / ios::out – (the defaults of ifstream and ofstream)ifstream and ofstream)

ios:nocreate / ios::noreplace – open only ios:nocreate / ios::noreplace – open only if the file exists / doesn’t existif the file exists / doesn’t exist

ios::trunc – open an empty fileios::trunc – open an empty fileios::binary – open a binary file (default ios::binary – open a binary file (default is textual)is textual)

Don’t forget to close the Don’t forget to close the file using the method file using the method “close()”“close()”

All rights reserved 12

1: To access file handling routines:#include <fstream.h>#include <fstream.h>

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 << "Input file open failed\n";{ cout << "Input file open failed\n";

exit(1);exit(1); // requires <stdlib.h>}// requires <stdlib.h>}

All rights reserved 13

5: To get data from a file (one option), must declare a variable to hold the data and then

read it using the extraction operator:int num;int num;

in_stream >> num;in_stream >> num;[Compare: cin >> num;][Compare: cin >> num;]

6: To put data into a file, use insertion operator:out_stream << num;out_stream << num;

[Compare: cout << num;][Compare: cout << num;]NOTE: Streams are sequential – data is read

and written in order – generally can't back up.7: When done with the file:in_stream.close();in_stream.close();out_stream.close();out_stream.close();

Stream state member Stream state member functionsfunctions

•In C++, file stream classes inherit a In C++, file stream classes inherit a stream state member from the ios class, stream state member from the ios class,

which gives out the information which gives out the information regarding the status of the stream.regarding the status of the stream.

For e.g.:For e.g.:–eof() –used to check the end of file eof() –used to check the end of file charactercharacter–fail()- used to check the status of fail()- used to check the status of file at opening for I/Ofile at opening for I/O–bad()- used to check whether invalid bad()- used to check whether invalid file operations or unrecoverable error file operations or unrecoverable error ..–good()- used to check whether the good()- used to check whether the previous file operation has been previous file operation has been successfulsuccessful

File operationsFile operations

The following member functions The following member functions are used for reading and writing are used for reading and writing a character from a specified a character from a specified file.file.get()- is used to read an get()- is used to read an alphanumeric character from a alphanumeric character from a file.file.put()- is used to write a put()- is used to write a character to a specified file or character to a specified file or a specified output streama specified output stream

Reading /Writing from/to Binary 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 <fstream.h>

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();}

All rights reserved 17

C++ has some low-level facilities for character C++ has some low-level facilities for character I/O.I/O.

char next1, next2, next3;char next1, next2, next3;cin.get(next1);cin.get(next1);

Gets the next character from the keyboard. Gets the next character from the keyboard. Does not skip over blanks or newline (\n). Can Does not skip over blanks or newline (\n). Can check for newline (next == '\n')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 <ctype.h> 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

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 << "Test Code: " << Chem1 << endl; else {

fin >> ratio; fin.get(Chem2); Chem2 = toupper(Chem2); cout << "Ratio of " << Chem1 << " to " << Chem2 << " is " << ratio << endl;

} new_line(fin); fin.get(Chem1); } }void new_line(istream& in){ char symbol; do {

in.get(symbol); } while (symbol != '\n');}

Reading /Writing from/to Textual Reading /Writing from/to Textual FilesFiles

• To write:– put() – writing single character

– << operator – writing an object

• To read:– get() – reading a single character of a buffer

– getline() – reading a single line

– >> operator – reading a object

#include <fstream.h>main(){

// Writing to fileofstream

OutFile("my_file.txt");OutFile<<"Hello "<<5<<endl;OutFile.close();

int number;char dummy[15];

// Reading from fileifstream

InFile("my_file.txt");InFile>>dummy>>number;

InFile.seekg(0); InFile.getline(dummy,sizeof(dummy));

InFile.close();}

All rights reserved 20

Binary file Binary file operationsoperations

In connection with a binary file, the file mode must contain the ios::binary mode along with other mode(s)To read & write a or on to a binary file, as the case may be blocks of data are accessed through the use of C++ read() and write() respectively.

All rights reserved 21

Random access file Random access file operationsoperations

Every file maintains two internal Every file maintains two internal pointers:pointers:

get_pointer and put_pointerget_pointer and put_pointerThey enable to attain the random access They enable to attain the random access in file otherwise which is sequential in file otherwise which is sequential in nature.in nature.

In C++ randomness is achieved by In C++ randomness is achieved by manipulating certain functionsmanipulating certain functions

Moving within the File

• seekg() / seekp() – moving the reading (get) / writing (put) marker– two parameters: offset and anchor

• tellg() / tellp() – getting the position of the reading (get) / writing (put) marker

All rights reserved 23

EOF and File I/O Within FunctionsEOF and File I/O Within FunctionsWhen using a file within a function, the When using a file within a function, the

file parameter file parameter MUST BEMUST BE a reference parameter: a reference parameter: int read_file(ifstream& infile);int read_file(ifstream& infile);

As with keyboard input, it is often As with keyboard input, it is often desirable to process some unknown amount desirable to process some unknown amount of data. We use the end-of-file (EOF) to of data. We use the end-of-file (EOF) to accomplish this. EOF is automatically accomplish this. EOF is automatically included in text files we create. included 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 bodyin_stream >> num;}in_stream >> num;}

All rights reserved 24

int main(){ ofstream out_stream; double d1, d2; char file_name[20]; // cstring cout << "Enter output file name: "; cin >> file_name; out_stream.open(file_name); if (out_stream.fail()) { cout << "Output file could not be opened.\n"; exit(1); } out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); cout << "Enter two numbers: "; cin >> d1 >> d2; out_stream << setprecision(2) << setw(10) << d1 << setw(10) << d1 * d1 << endl; out_stream << setprecision(2) << setw(10) << d2 <<setw (10) << d2 * d2 << endl; out_stream.close();}

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 << setw(7) << "Side 1" << setw(7) << "Side 2" << setw(7) << "Side 3" << setw(7) << "Area" << setw(12) << "Perimeter\n"; in_stream >> side1; while (! in_stream.eof()) // true AFTER attempt to read beyond eof { in_stream >> side2 >> side3; compute(side1, side2, side3, perimeter, area); cout << setw(5) << side1 << setw(7) << side2 <<setw(7) << side3 << setw(9) << area << setw(10) << perimeter << endl; in_stream >> side1; } in_stream.close();}

All rights reserved 26

void open_input_file(ifstream& instream){ instream.open("lengths.dat");

if (instream.fail()) { cout << "Input file could not be opened.\n";

exit(1); } }void compute(int side1, int side2, int side3, int& perimeter, double& area){ double s; perimeter = side1 + side2 + side3; s = perimeter / 2.0; area = sqrt (s * (s - side1) * (s - side2) * (s - side3));}

All rights reserved 27

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 either readable form or in binary code called as text file or binary file.

• The flow of data from any source to a sink is called as a stream.

All rights reserved 28

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 in the 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