24
Multifile Program Chapter 13

Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Embed Size (px)

Citation preview

Page 1: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Multifile ProgramChapter 13

Page 2: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Binary FilesIn binary files we do not need to format dataFile streams include two member functions specifically

designed to input and output binary data sequentiallyWrite

A member function of ostream inherited by ofstreamRead

A member function of istream that is inherited by ifstream

write ( memory_block, size );read ( memory_block, size );

Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where data elements are read and write

The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.

Page 3: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

#include <iostream> #include <fstream> ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) {

size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory";

delete[] memblock; } else

cout << "Unable to open file"; return 0; }

Page 4: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Class librariesLibraries provide ready-made functions A class library can take over a greater programming

burdenClass developer vs programmerClass library consists of various public declarations Class library comes under header file with .H extensionClass library is used in source code with #includeThe declarations are interface to the programmerImplementation details (source code) are hidden from

programmer.Source code is distributed in OBJ files or library(.LIB) files

Page 5: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Organization and conceptualizationLarge programs can be broken into multiple

filesMany programmers are working with same

projectTheirs.h

Theirs.obj Mine.obj

Mine.cpp Mine.h

Theirs.lib

Mine.exe

Compiler

Linker

Page 6: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Cont’dHeader file can be included in source file like

#include “theirs.h”Quotes tell the compiler to look for the file in

current directoryEach complier keeps its own library files in

INCLUDE directoryA project contains all the files necessary for

application

Page 7: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Interfile Communication - variablesA variable is declared by giving it a name and typeA variable is defined when it is given a place in memoryTo access a variable in different files, it must be declared in

every file//File A

int globalvar//File B

globalvar = 3 // illegal, unknown to file Bextern int globalvar // OK

globalvar = 3;Use extern keyword to declare it in other file.extern causes globalvar in file A to be visible in file BThe linker will take care of connecting reference to a variable

Page 8: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Inter-file functionsFunction declaration vs function definition?Compiler only needs to know function name, its return

type and the types of its argumentsTo use function defined in one file we only need to

declare the function in second file//File A

int add(int a, int b){return a+b;}//File B

int add(int,int);. . .

int answer = add(3,2); //call to functionNo need to use keyword extern

Page 9: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Inter-file classesDefinition of class does not set aside memory

unless an object is declaredTo access a class in multi files, it must be

declared in each file in which its object will be used

The compiler needs to know the data type of everything its compiling like variables, functions

Class definition holds these thing

Page 10: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Header filesCommon information needs for many filesHeader file holds variable or function declarationsDefinitions of functions and variable in header file will generate

“multiply define” errorA class definition does not create multiply define error//FileH.hextern int globar; int gloFunc(int);//FileA.cpp#include “fileH.h”int glovar; int gloFunc(int n){ return n; }//FileB.cpp #include “fileH.h”glovar= 5;Int glovarB = gloFunc(glovar);

Page 11: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Example //fileH.hclass someClass{Private: int memvar:Public: int memFunc(int,int);};//fileA.cpp#include “fileH.h”Int someClass::memFunc(int n1, int n2){return n1+n2;}//fileB.cpp#include “fileH.h”someClass anObj;Int answer = anObj.memFunc(6,7);

Page 12: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Multiple Includes Hazard Including the same header file twice in source file causes multiple-definition

errors//file headtwo.hInt globalVar;//file headone.h#include headtwo.h//file aap.cpp#include “headone.h”#include “headtwo.h”int globalvar; // from headtwo.h via headone.hint globalvar; // from headtwo.h To avoid from such hazard use #if and #define directives#if !define(HEADCOM)#define HEADCOM…………#endif

Page 13: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

NamespacesNamespaces allow to group entities like classes,

objects and functions under a namenamespace identifier{entities}Identifier is any name given to name space and

entities are group of classes, functions, variablesIts useful when global object of function uses

same variable. Using keyword is used to introduce namespace in

program

Page 14: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Example #include <iostream> namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; }

Page 15: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Template and ExceptionsChapter 14

Page 16: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Function templateFunction templates are special functions that can

operate with generic typesFunction template can be adapted for more than one

type of data instead of repeating entire codeIn C++ this can be achieved using template

parametersA template parameter is use to pass type as function

arguments like values are passed in simple functionThe format for declaring function templates with type

parameters is:template <class identifier> function_declaration;

Page 17: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Example #include <iostream> template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0; }

Page 18: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Cont’dWe can also define function templates that

accept more than one type parametertemplate <class T, class U> T GetMin (T a, U b) { return (a<b?a:b); }We can use this function asint i,j;long l; i = GetMin<int,long> (j,l);ORi = GetMin (j,l);

Page 19: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Class TemplateClass templates are generally used for data

storage(container) classestemplate <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };The object of class template is declared as

mypair<int> myobject (115, 36); Mypair<float> floatobject(12.3,35.4);

Page 20: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Example#include <iostream> template <class T> class mypair { T a, b; public: mypair (T first, T second){a=first; b=second;} T getmax (); };

template <class T>T mypair<T>::getmax () {T retval; retval = a>b? a : b; return retval; } int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; }

Page 21: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

ExceptionsExceptions provide a way to react to runtime

errors in a program by transferring control to special functions called handlers

To catch exceptions code is placed under exception inspection i.e. try block

When exception is occurred control is transferred to exception handlers otherwise code run normally

The exception handlers are declared with keyword catch

Page 22: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Cont’d#include <iostream> int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. "; } return 0; }Throw expression accepts one parameter which is

passed as an argument to the exception handler

Page 23: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Sequence of eventsCode is executing normally outside a try

blockControl enters the try blockA statement in the try block causes an error

in a member functionThe member function throws an exceptionControl transfers to the exception handler

(catch block) following the try block

Page 24: Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output

Multiple catch()Multiple catch statements can be included

each have different parameter typeBy using ellipsis (…) as parameter of catch

the handler can catch any exception regardless of type

try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; } catch (...) { cout << "default exception"; }