A A A A

Guided by:

Data File Handling in C++

A A

N Rakhesh
PGT (Comp. Science) Kendriya Vidyalaya Railway Colony Bangalore

Topics - Agenda
‡ Introduction ‡ Opening & closing of files ‡ Stream state member functions ‡ File operations ‡ Binary file operations ‡ Random access file operations ‡ CBSE Question Pattern from this topic ‡ Conclusion
All rights reserved 2

‡ 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 fstream. ‡ 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.
All rights reserved 3

Introduction

programs. Every stream is associated with a class having member functions and operations for a particular kind of data flow. included in all file handling programs.h and hence needs to be fstream.The fstream. Diagrammatically as shown in next slide . data. They represent as a sequence of bytes and deals with the flow of data.reads Program File (Output stream) ² write All designed into fstream.h header file Streams act as an interface between files and programs. programs. File Program ( Input stream) . flow.

All rights reserved 5 .

File Handling Classes Hierarchy Diagram .

ios istream streambuf ostream iostream ifstream fstream ofstream filebuf fstreambase All rights reserved 7 .

‡Store data permanently (until file is deleted).Why to use Files: ‡Convenient way to deal large quantities of data. ‡Avoid typing data into program multiple times. 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 . ‡Share data between programs.

if (in_stream.open("numbers. exit(1).fail()) { cout <<"Output file could not opened.// Initial experience reading and writing files #include <fstream. out_stream << "The square of " << num << " is " <<num * num.\n".h> #include <stdlib.\n".h> #include <iostream. exit(1). } in_stream >> num.close(). ofstream out_stream.fail()) { cout << "Input file could not be opened.open("squares.dat"). if (out_stream. in_stream. int num.dat").h> int main() { ifstream in_stream. } out_stream. out_stream. All rights reserved 9 } . in_stream.close().

‡ ofstream inherits from the class ostream (standard output class). the 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 cout? ² When ever we include <iostream. pointing to stdout is automatically defined ² this object is cout. ‡ ostream overloaded the operator >> for standard output.File Handling Classes ‡ When working with files in C++. .«thus an ofstream object can use methods and operators defined in ostream. an ostream object.h>.

 filename ² file to open (full path or local)  mode ² how to open (1 or more of following ² using | ) ios::app ² append ios::ate ² open with marker at the end of the file ios::in / ios::out ² (the defaults of ifstream and ofstream) ios:nocreate / ios::noreplace ² open only if the file exists / doesn·t exist ios::trunc ² open an empty file ios::binary ² open a binary file (default is textual)  Don·t forget to close the file using the method ´close()µ . void ofstream / ifstream::open(const char* filename.Opening & Closing a File  A file can be open by the method ´open()µ or immediately in the constructor (the natural and preferred way). int mode).

open("outfile.. ofstream out_stream.fail()) { cout << "Input file open failed\n".e.h> 2: To declare variables that can be used to access file: ifstream in_stream.1: To access file handling routines: #include <fstream.dat"). failed\ exit(1).h>} All rights reserved 12 . on the Unix file system): in_stream.dat"). 3: To connect your program's variable (its internal name) to an external file (i. 4: To see if the file opened successfully: if (in_stream. out_stream. // requires <stdlib.open("infile.

use insertion operator: out_stream << num. All rights reserved 13 . [Compare: cout << num.close().] 6: To put data into a file. out_stream.close(). must declare a variable to hold the data and then read it using the extraction operator: int num. in_stream >> num. 7: When done with the file: in_stream. [Compare: cin >> num.] NOTE: Streams are sequential ± data is read and written in order ± generally can't back up.5: To get data from a file (one option).

used to check the status of file at opening fail()for I/O ²bad(). which gives out the information regarding the status of the stream.used to check whether invalid file bad()operations or unrecoverable error .g. For e.used to check whether the previous file good()operation has been successful . file stream classes inherit a stream state member from the ios class.: ²eof() ²used to check the end of file character ²fail(). ²good().Stream state member functions ‡In C++.

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

OutBinaryFile.7.h> main() { int array[] = {10.23.txt³. ofstream OutBinaryFile("my_b_file. } . int n).close().Reading /Writing from/to Binary Files ‡ To write n bytes: ² write (const unsigned char* buffer.253}.9. sizeof(array)). OutBinaryFile. ios::out | ios::binary).11.3. ‡ To read n bytes (to a pre-allocated buffer): ² read (unsighed char* buffer.write((char*) array. int num) #include <fstream.

next3.get(next2). Can check for newline (next == '\n') (\ '\ Example: cin. lowchar next1.get(next3). cin.CHARACTER I/O C++ has some low-level facilities for character I/O. cin. Gets the next character from the keyboard.get(next1).get(next1). cin. Does not skip over blanks or newline (\n).h> and can be used to convert between upper and lower case test whether in upper or lower case test whether alphabetic character or digit test for space All rights reserved 17 . next2. Predefined character functions must #include <ctype.

else { fin >> ratio. // open error check omitted for space fin. cout << "Ratio of " << Chem1 << " to " << Chem2 << " is " << ratio << endl. All rights reserved } while (symbol != '\n'). void main() omitted for space ifstream fin. double ratio. while (!fin. } 18 .//#include. fin.get(symbol). Chem2 = toupper(Chem2).open("input. fin. do { in. } new_line(fin).get(Chem1).eof()) { if (isdigit(Chem1)) cout << "Test Code: " << Chem1 << endl.get(Chem2). } } void new_line(istream& in) { char symbol. char Chem1. fin.get(Chem1). prototypes. Chem2.dat").

OutFile.getline(dummy. InFile. } ‡ To read: ² get() ² reading a single character of a buffer ² getline() ² reading a single line ² >> operator ² reading a object .Reading /Writing from/to Textual Files ‡ To write: ² put() ² writing single character ² << operator ² writing an object #include <fstream. InFile.sizeof(dummy)).close().h> main() { // Writing to file ofstream OutFile("my_file. // Reading from file ifstream InFile("my_file.seekg(0). OutFile<<"Hello "<<5<<endl.txt"). InFile>>dummy>>number.close(). InFile.txt"). int number. char dummy[15].

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

Random access file operations Every file maintains two internal pointers: get_pointer and put_pointer They enable to attain the random access in file otherwise which is sequential in nature. In C++ randomness is achieved by manipulating certain functions All rights reserved 21 .

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 .

EOF is automatically included in text files we create.EOF and File I/O Within Functions When using a file within a function. We use the end-of-file end-of(EOF) to accomplish this. it is often desirable to process some unknown amount of data. the file parameter MUST BE a reference parameter: int read_file(ifstream& infile). // priming read while (! in_stream.eof()) {loop body in_stream >> num. while (in_stream >> num) OR in_stream >> num.} All rights reserved 23 . As with keyboard input. Can test for EOF in several ways.

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

setf(ios::fixed).eof()) // true AFTER attempt to read beyond eof { in_stream >> side2 >> side3. cout. perimeter. side3. in_stream >> side1.int main() { int side1. double area. cout << setw(7) << "Side 1" << setw(7) << "Side 2" << setw(7) << "Side 3" << setw(7) << "Area" << setw(12) << "Perimeter\n".close(). open_input_file(in_stream). compute(side1. while (! in_stream. cout. side2. All rights reserved 25 } . ifstream in_stream. perimeter. area).setf(ios::showpoint). cout.precision(2). } in_stream. cout << setw(5) << side1 << setw(7) << side2 <<setw(7) << side3 << setw(9) << area << setw(10) << perimeter << endl. side2. side3. in_stream >> side1.

double& area) { double s. s = perimeter / 2. int side2. int side3.void open_input_file(ifstream& instream) { instream. int& perimeter. area = sqrt (s * (s .\n".side2) * (s . } All rights reserved 26 . perimeter = side1 + side2 + side3.dat").side3)). } } void compute(int side1.side1) * (s .0.fail()) { cout << "Input file could not be opened. if (instream.open("lengths. exit(1).

CBSE QUESTION PATTERN RELATED TO DATA FILE HANDLING .

‡ Bases classes are used to perform I/O operations.Summary ‡ Files in C++ are interpreted as a sequence of bytes stored on some storage media. ‡ The flow of data from any source to a sink is called as a stream. All rights reserved 28 . ‡ The data of a file is stored in either readable form or in binary code called as text file or binary file.

A variety of options are available for controlling the appearance of the output. fail().setf(ios::showpoint). 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.precision(2). good(). and may intermix keyboard/ display I/O with file I/O. Flags to control floating point display: ‡ out_stream. clear() is used to clear the status bits (after they were checked). One program may have multiple input and/or output files.setf(ios::fixed). rather than hard coded in the program. cannot be used. 5. We can also access the bit we wish to check with eof(). 4. bad(). When getting data from a file. 3. but alright to continue ‡ ios:badbit ² corrupted file.More Information on File I/O 1. The file name may be obtained from the user. ‡ out_stream. there is no need to prompt for input. . 2. The layout of a program's output is called the format. ‡ out_stream. All rights reserved 29 8. 7.

Questions ? ? All rights reserved 30 .

Science KVS .Presented by: N RAKHESH PGT Comp.

Sign up to vote on this title
UsefulNot useful