File Processing
• Files are used for data persistance-permanent retention of large amounts of data.
• Computer store files on secondary storage devices ,such as magnetic disks,optical disks and tapes.
• Create a file
• Update a file
• Process data files
Files and Stream
• When a file is opened, an object is created and a stream is associated with the object
• Cin, cout, cerr and clog are created when
<iostream> is included.
• The streams associated with these objects provide communication channels between a program and a particular file or device.
• Example: cin object (standard input stream object) enables a program to input data from the keyboard or from other devices
Cont…
• Cout object (standard output stream object) enables a program to output data to the screen.
• Cerr and clog objects(standard error stream objects) enable a program to output error message.
Cont…
• File processing – header files<iostream> and
<fstream> must be included.
• Header <fstream> includes the definitions for the stream class templates basic _if stream(for file input), basic _of stream (for file output) and basic_fstream(for file input and output).
• Each class template has a predefined template specialization that enables char I/O.
Cont…
• Files are opened by creating objects of these stream template specializations.
• These templates “derive” from class templates basic_istream, basic_ostream and basic_iostream respectively.
• All member functions,operators and manipulators that belong to these templates also can be applied to file streams.
Cont…
• Details of file stream classes:
• Filebuf - its purpose is to set the file buffers to read and write. Contains open() of file stream classes, also contains close() and open() as members.
• Fstreambase - Provides operations common to the file streams.serves as a base for fstream,ifstream and ofstream classes.
Contains open() and close() functions.
Cont…
• Ofstream – provides output operations.
Contains open() with default output mode.
• inherits put(),seek(),write() functions from ostream.
• Fstream – Provides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream.
Creating a sequential file
• Record does not exist in c++ file.
• The programmer must structure files to meet the application’s requirements
• The file stream classes support a number of member functions for performing the input and output operations on files.
• Put() and get() are designed for handling a single character at a time.
Cont…
• The function put() writes a single character to the associated stream.
• The function get() reads a single character from the associated stream.
• Example:
• #include <fstream.h>
• #include <string.h>
• Main()
• {
Char string(20);
Cout<<“Enter a string\n”;
Cin>> string;
{
Int len = strlen(string);
Fstream file; //input and output stream
File.open (“Text” , ios:: in : ios::out);
For (int i=0; i<len; i++) file.put(string[i] ); \\ put a character to file
File .seekg(0);
Char ch;
While (file) file.get(ch); \\get a character from file cout << ch; \\display it on screen
Reading data from a sequential file
• Since fstream object can handle both the input and output simultaneously
• We can open the file in ios::in and ios::out mode.
• To read the entire file
• File.seekg(0);
• Files store data and it may be retrieved for processing when needed.
Cont…
• Creating an if stream object opens a file for input.
• The ifstream constructor can receive the filename and file open mode as arguments.
• The arguments in parentheses are passed to the ifstream constructor function, which opens the file and establishes a “line of communication” with the file.
Cont…
• #include <iostream>
• Using std :: cerr;
• Using std :: cout;
• Using std :: endl;
• Using std :: fixed;
• Using std :: ios;
• Using std :: left;
• Using std :: right;
• Using std :: showpoint;
Cont…
• # include <fstream>
• Using std :: ifstream; //input file stream
• # include <iomanip>
• Using std :: setw;
• Using std :: setprecision;
• #include <string>
• Using std:: string;
• #include <cstdlib>
• Using std ::exit; //exit function prototype
• Void outputline (int,const string,double);
Cont…
• Int main()
• {
• // ifstream constructor opens the file
• Ifstream inclientfile (“clients.dat”,ios::in);
• //exit program if ifstream could not open file
• If (!inclientfile)
• { cerr<<“file could not be opened”<<endl; exit(1);
} //end if
Cont…
• Int account;
• Char name[30];
• Double balance;
• Cout<<left<<setw (10)<< “account” <<setw
(13)
• <<“name”<<“balance”<<endl<<fixed<<showp oint;
• //display each record in file
Cont…
• //display each record in file
• While (inclientfile>>account>>name>>balance)
• outputLine(account,name,balance);
• return 0;
• } //end main
• //display single record from file
• Void outputLine(int account,const string name,double balance)
Cont…
• { cout <<left<<setw(10) <<account <<setw(13) <<name
<<setw(7) <<setprecision(2) <<right<<balance<<endl;
}//end function outputLline
Account Name Balance
100 Jones 24.95
200Doe 345.67
300 white -42.16
Creating a binary file
• Pair of functions, write() and read() designed to write and read binary data
• The values are stored in disk file in the same format in which they are stored in the internal memory.
• An int takes two bytes to store its value in the binary form, irrespective of its size.
• The binary format is more accurate for storing the numbers as they are stored in the exact internal representation.
• There are no conversions while saving the data and therefore saving is much faster.
• Binary format :
2 bytes
00000010
Cont…
00100010
• Character format:
• 4 bytes
2 3 7 4
Cont…
• These infile.read((char*) &v, sizeof(v));
• outfile.write((char*)&v,sizeof(v));
• These functions take two arguments. The first is the address of the variable v, and the second is the length of that variable in bytes.
• The address of the variable must be cast to type char* (i.e. pointer to character type).
Cont…
• # include <fstream.h>
• #include <iomanip.h>
• Const char * filename = “BINARY”;
• Main()
• { float height(4)=(20.3, 34.0, 56.7, 48.7); ofstream outfile(filename); outfile.write((char*) & height, size of (height)); outfile.close(); //close file for reading for (int i=0; i<4; i++) //clear array from memory height(i) =0; ifstream infile(filename);
{ infile.read((char*) & height, size of (height)); for (i=0; i< 4; i++) cout.setf(ios::showpoint); cout<<setw(10) << setprecision(2)
<<height(i);
}
Updating sequential file
• Data that is formed and written to a sequential file cannot be modified without the risk of destroying other data in the file
• Example
• If the name “white” needs to be changed to
“liva” the old name cannot be overwritten without corrupting the file
Random-access files,
• If all the records in a file be of the same fixed length. Using same-size, fixed-length records
• Data can be inserted into a random-access file without destroying other data in the file.
• Data stored previously also can be updated or deleted without rewriting the entire file.
Creating a random –access file
• The ostream member function write outputs a fixed number of bytes, beginning at a specific location in memory, to the specified stream.
• When the stream is associated with a file
,function write writes the data at the location in the file specified by the “put”file-position pointer.
• The istream member function read inputs a fixed number of bytes from the specified stream to an area in memory beginning at a specified address.
Cont…
• If the stream is associated with a file,function read inputs bytes at the location in the file specified by the “get” file-position pointer
• Writing bytes with ostream member function write
- When writing an integer number to a file, instead of using statement outfile<<number;
• Converting between pointer types with the reinterpert_cast operator
• Writes data to the file and uses the combination of fstream functions seekp and write to store data at exact locations in the file.
• Function seekp sets the “put” file-position pointer to a specific position in the file and then write outputs the data.
• Example
• #INCLUDE <IOSTREAM>
• Using std ::cerr;
• Using std ::cin;
• Using std ::cout;
• Using std :: endl;
• Using std ::ios;
• #include <iomanip>
• Using std::setw;
• #include <cstdlib>
• Using std :: exit;
• #include “clientdata.h”
Cont…
• Int main()
• { int accountnumber;
Char lastname(15);
{
Char firstname(10);
Double balance;
Fstream outcredit(“credit.dat”,ios::in/ios::out/ios::binary);
If (!outcredit) cerr<<“file could not be opened.”<<endl; exit(1);
}
Cout<<“enter account number ( 1 to 100, 0 to end input)\n?”;
Cont…
• Clientdata client;
• Cin>>accountnumber;
• While (accountnumber> 0 && accountnumber<= 100)
• Cout<<“enter lastname, first name, balance\n?”;
• Cin>>setw(15) >> lastname;
• Cin>>setw(10) >> firstname;
• Cin>> balance;
• Client.setaccountnumber(accountnumber);
• Client.setlastname(lastname);
• Client.setfirstname(firstname);
• Client.setbalance(balance);