Presentation is loading. Please wait.

Presentation is loading. Please wait.

UNIT-V Files.

Similar presentations


Presentation on theme: "UNIT-V Files."— Presentation transcript:

1 UNIT-V Files

2 Classes For File Handling
C++ uses file streams as an interface between the programs and the data files. Input Stream Read Data Data input Disk Files Program Output Stream Write Data Data output

3 File Input and Output Stream
The stream that supplies data to the program is known as input stream Input stream extracts (or read) data from file Input Stream Read Data Data input Disk Files Program Output Stream Write Data Data output The stream that receives data from the program is known as output stream Output stream inserts (or writes) data to the file

4 Opening Files For opening a file, we must first create a file stream and then link it to the filename. A file stream can be defined using the classes ifstream, ofstream, and fstream that are contained in the header file fstream. The class to be used depends on read or write. A file can be open in two ways: Using the constructor function of the class. Useful when we use only one file in the stream. Using the member function open( ) of the class. Use to manage multiple files using one stream.

5 Opening Files Using Constructor
This involves two steps: Create a file stream object to manage the stream using appropriate class. The class ofstream used to create output stream. The class ifstream to create input stream. Initialize the file object with the desired filename.

6 Opening Files Using Constructor
continue … ofstream outfile (“results”); ifstream infile(“data”); Disk Output Stream Result File outfile Program Input Stream Data File infile

7 Opening Files Using Open( )
The open( ) can be used to open multiple files that use the same stream object. For processing a set files sequentially. file-stream-class stream-object; stream-object.open ( “file_name” );

8 Opening Files Using Open( )
continue … ofstream outfile; outfile.open(“DATA1”); …….. outfile.close( ); outfile.open(“DATA2”); ……… The above program segment opens two files in sequence for writing the data. The first file is closed before opening the second one. A stream can be connected to only one file at a time.

9 Detecting End-Of-File
while (fin) An ifstream object fin returns a value 0 if any error occurs in the file operation including the end-of-file condition. So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition. if(fin1.eof() != 0) {exit(1);} eof( ) is a member of ios class. It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a zero, otherwise.

10 File Modes stream-object.open(“file_name”, mode);
The second argument mode specifies the purpose for which the file is opened. Default values for these second parameters: ios::in – for ifstream - reading only ios::out – for ofstream - writing only

11 File Modes ios::app  Append to end-of-file
continue … ios::app  Append to end-of-file ios::ate  Go to end-of-file on opening ios::binary  Binary file ios::in  Open file for reading only ios::nocreate  Open fails if the file does not exist ios::noreplace  Open files if the file already exists ios::out  Open file for writing only ios::trunc  Delete the contents of the file if it exists fout.open(“data”, ios::app | ios :: nocreate)

12 File Pointer Input Pointer (get pointer) Output Pointer (put pointer)
The input pointer is used for reading contents of a given file location. Output Pointer (put pointer) The output pointer is used for writing to a given file location. Each time an input or output operation takes place, the appropriate pointer is automatically advanced.

13 File Pointer – Default Actions
When a file opened in read-only mode, the input pointer is automatically set at the beginning of the file. When a file is opened in write-only mode, the existing contents are deleted and the output pointer is set at the beginning. When a file is opened in append mode, the output pointer moves to the end of file.

14 Functions for Manipulations of File Pointers
seekg( )  Moves get pointer (input) to a specified location. seekp( )  Moves put pointer(output) to a specified location. tellg( )  Gives the current position of the get pointer. tellp( )  Gives the current position of the put pointer.

15 Seek Function with Absolute Position
infile.seekg(10); Moves the file pointer to the byte number 10. The bytes in a file are numbered beginning from zero. Therefore, the pointer pointing to the 11th byte in the file.

16 Seek Function with Specifying the Offset
seekg( offset, refposition); seekp( offset, refposition); The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class: ios : : beg  start of the file ios : : cur  current position of the pointer ios : : end  end of the file

17 Seek Function with Specifying the Offset
fout.seekg(0, ios : : beg); Go to start fout.seekg(0, ios : : cur); Stay at the current position fout.seekg(0, ios : : end); Go to the end of file fout.seekg(m, ios : : beg); Move to (m+1)th byte in the file fout.seekg(m, ios : : cur); Go forward by m bytes from the current position fout.seekg(-m, ios : : cur); Go backward by m bytes from the current position fout.seekg(-m, ios : : end) Go backward by m bytes from the end

18 Sequential Input and Output Operations
put( ) and get( ) Functions The function put( ) writes a single character to the associated stream. The function get( ) reads a single charracter from the associated stream.

19 Sequential Input and Output Operations
continue … write( ) and read( ) Functions The functions write( ) and read ( ) handle the data in binary form. The values are stored in the 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. But a 4 digit int will take four bytes to store it in the character form.

20 Sequential Input and Output Operations
continue … Representing 2594 I 2 Bytes I Binary Format I 4 Bytes I 2 5 9 4 Character Format

21 Sequential Input and Output Operations
continue … infile.read((char *) &V, sizeof(V)); outfile.write((char *) &V, sizeof(V)); write( ) and read( ) functions take two arguments. First is the address of the variable V Second is the length of that variable in bytes. The address of the variable must be cast to type char * (pointer to character type).

22 Reading and Writing a Class Object
The read( ) and write( ) are also used to read from or write to the disk files objects directly. The read( ) and write( ) handle the entire structure of an object as a single unit, using the computer’s internal representation of data. Only data members are written to the disk files.

23 Updating A File : Random Access
The size of each object can be obtained using the statement int object_length = sizeof(object); The location of a desired object, say mth object int location = m * object_length; The location gives the byte number of the first byte of the mth object. Now we can use seekg( ) or seekp( ) to set the file pointer to reach this byte.

24 Updating A File : Random Access
continue … To find the total number of objects in a file using object_length int n = file_size / object_length; The file size can be obtained using the function tellg( ) or tellp( ) when the pointer is located at the end of the file.

25 Error Handling During File Operations
A file which we are attempting to open for reading does not exist. The file name used for a new file may already exist. We may attempt an invalid operation such as reading past the end-of-file. There may not be any space in the disk for storing more data. We may use an invalid file name. We may attempt to perform an operation when the file is not opened for that purpose.

26 Error Handling During File Operations
continue … The C++ file stream inherits a “stream_state” member from the class ios. This member records information on the status of a file that is being currently used. The class ios supports several member functions that can be used to read the status recorded in a file stream. eof( ) fail( ) bad( ) good( ), etc.

27 Command – Line Arguments
C++ supports a feature that facilitates the supply of argument to the main( ) function. These arguments are supplied at the time of invoking the program. They are typically used to pass the names of data files. Eg:- exam data result The command-line arguments are typed by the user and are delimited by a space.

28 Command – Line Arguments
continue … The main function can take two arguments. main( int argc, char * argv [ ] ) The first argument argc (argument counter) represents the number of arguments in the command line. The second argument argv (argument vector) is an array of char type pointers that points to the command line arguments. The size of the array will be equal to the value of argc.

29 Command – Line Arguments
continue … C:\> exam data results The value of argc would be 3 and argv would be an array of three pointers to strings as: argv[0]  exam argv[1]  data argv[2]  results …… infile.open(argv[1]); outfile.open(argv[2]);

30 Templates Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures. A significant benefit of object oriented programming is reusability of code which eliminates redundant coding. An important feature of C++ called templates strengthens this benefit of OOP and provides great flexibility to the language. Templates support generic programming, which allows to develop reusable software components such as functions, classes etc.. supporting different data types in a single framework.

31 Templates Templates Concept
Instead of writing different functions for the different data types, we can define common function. For example int max(int a,int b); // Returns maximum of two integers float max(float a,float b); // Return maximum of two floats char max(char a,char b); // Returns maximum of two characters (this is called as function overloading) But, instead of writing three different functions as above, C++ provided the facility called "Templates". With the help of templates you can define only one common function as follows: T max(T a,T b); // T is called generic data type

32 Templates Features of templates:- It eliminates redundant code
It enhances the reusability of the code. It provides great flexibility to language Templates are classified into two types. They are 1.Function templates 2.Class Templates.

33 Function Templates The templates declared for functions are called as function templates. A function template defines how an individual function can be constructed. General Form of a Function Template

34 Function Templates with Multiple Parameters
Like template class, we can use more than one generic data type in the template statement, using a comma-separated list as shown below:

35 Class Templates The templates declared for classes are called class templates. A class template specifies how individual classes can be constructed similar to the normal class specification. These classes model a generic class which support similar operations for different data types. General Form of a Class Template

36 Class Templates with Multiple Parameter
General Form of a Class Template

37 Exception Handling

38 Introduction Exceptions are errors or some peculiar problems other than logic or syntax errors. Exceptions are runtime anomalies or unusual conditions that a program may encounter while executing.

39 Introduction Anomalies includes : Division by zero
Access to an array outside of its bounds Running out of memory or disk space

40 Basics of Exception Handling
The purpose of exception handling mechanism is to provide means to detect and report an exceptional circumstances so that appropriate action can be taken. Exceptions are of two types: Synchronous Exception Out-of-range index Over-flow Asynchronous Exception Keyboard interrupts

41 Basics of Exception Handling
The mechanism has error handling code that perform the following tasks: Find the problem ( Hit the exception ) Inform that an error has occurred ( Throw the exception ) Receive the error information ( Catch the exception ) Take corrective actions ( Handle the exception )

42 Exception Handling Mechanism
The error handling code basically consists of two segments: One to detect errors and to throw exceptions Other to catch the exceptions and to take appropriate actions.

43 Standard Template Library
The standard template library (STL) contains Containers Algorithms Iterators A container is a way that stored data is organized in memory, for example an array of elements. Algorithms in the STL are procedures that are applied to containers to process their data, for example search for an element in an array, or sort an array. Iterators are a generalization of the concept of pointers, they point to elements in a container, for example you can increment an iterator to point to the next element in an array

44 Containers, Iterators, Algorithms
Algorithms use iterators to interact with objects stored in containers Container Container Iterator Algorithm Iterator Objects Algorithm Iterator Iterator Algorithm

45 Containers A container is a way to store data, either built-in data
types like int and float, or class objects The STL provides several basic kinds of containers <vector> : one-dimensional array <list> : double linked list <deque> : double-ended queue <queue> : queue <stack> : stack <set> : set <map> : associative array

46 Sequence Containers A sequence container stores a set of elements in
sequence, in other words each element (except for the first and last one) is preceded by one specific element and followed by another, <vector>, <list> and <deque> are sequential containers In an ordinary C++ array the size is fixed and can not change during run-time, it is also tedious to insert or delete elements. Advantage: quick random access <vector> is an expandable array that can shrink or grow in size, but still has the disadvantage of inserting or deleting elements in the middle

47 Sequence Containers <list> is a double linked list (each element has points to its successor and predecessor), it is quick to insert or delete elements but has slow random access <deque> is a double-ended queue, that means one can insert and delete elements from both ends, it is a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes a compromise between a <vector> and a <list>

48 Associative Containers
An associative container is non-sequential but uses a key to access elements. The keys, typically a number or a string, are used by the container to arrange the stored elements in a specific order, for example in a dictionary the entries are ordered alphabetically.

49 Associative Containers
A <set> stores a number of items which contain keys The keys are the attributes used to order the items, for example a set might store objects of the class Person which are ordered alphabetically using their name A <map> stores pairs of objects: a key object and an associated value object. A <map> is somehow similar to an array except instead of accessing its elements with index numbers, you access them with indices of an arbitrary type. <set> and <map> only allow one key of each value, whereas <multiset> and <multimap> allow multiple identical key values

50 Vector Container int array[5] = {12, 7, 9, 21, 13 };
vector<int> v(array,array+5); 12 7 9 21 13 v.push_back(15); v.pop_back(); 13 12 7 9 21 12 7 9 21 15 12 7 9 21 15 v.begin(); v[3]

51 Vector Container #include <vector> #include <iostream>
vector<int> v(3); // create a vector of ints of size 3 v[0]=23; v[1]=12; v[2]=9; // vector full v.push_back(17); // put a new value at the end of array for (int i=0; i<v.size(); i++) // member function size() of vector cout << v[i] << ” ”; // random access to i-th element cout << endl;

52 Vector Container #include <vector> #include <iostream>
int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array while ( ! v.empty()) // until vector is empty { cout << v.back() << ” ”; // output last element of vector v.pop_back(); // delete the last element } cout << endl;

53 Constructors for Vector
A vector can be initialized by specifying its size and a prototype element or by another vector vector<Date> x(1000); // creates vector of size 1000, // requires default constructor for Date vector<Date> dates(10,Date(17,12,1999)); // initializes // all elements with vector<Date> y(x); // initializes vector y with vector x

54 vector<int>::iterator
Iterators Iterators are pointer-like entities that are used to access individual elements in a container. Often they are used to move sequentially from element to element, a process called iterating through a container. vector<int> array_ 17 vector<int>::iterator 4 23 The iterator corresponding to the class vector<int> is of the type vector<int>::iterator 12 size_ 4

55 Iterators The member functions begin() and end() return an
iterator to the first and past the last element of a container vector<int> v v.begin() array_ 17 4 23 v.end() 12 size_ 4

56 Iterators One can have multiple iterators pointing to different or identical elements in the container vector<int> v i1 array_ 17 4 i2 23 12 i3 size_ 4

57 Iterators #include <vector> #include <iostream>
int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array vector<int>::iterator iter=v.begin(); // iterator for class vector // define iterator for vector and point it to first element of v cout << ”first element of v=” << *iter; // de-reference iter iter++; // move iterator to next element iter=v.end()-1; // move iterator to last element

58 Iterators int max(vector<int>::iterator start, vector<int>::iterator end) { int m=*start; while(start != stop) if (*start > m) m=*start; ++start; } return m; cout << ”max of v = ” << max(v.begin(),v.end());

59 Iterators #include <vector> #include <iostream>
int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array for (vector<int>::iterator i=v.begin(); i!=v.end(); i++) // initialize i with pointer to first element of v // i++ increment iterator, move iterator to next element { cout << *i << ” ”; // de-referencing iterator returns the // value of the element the iterator points at } cout << endl;

60 Iterator Categories Not every iterator can be used with every container for example the list class provides no random access iterator Every algorithm requires an iterator with a certain level of capability for example to use the [] operator you need a random access iterator Iterators are divided into five categories in which a higher (more specific) category always subsumes a lower (more general) category, e.g. An algorithm that accepts a forward iterator will also work with a bidirectional iterator and a random access iterator input forward bidirectional random access output

61 For_Each() Algorithm #include <vector>
#include <algorithm> #include <iostream> void show(int n) { cout << n << ” ”; } int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array for_each (v.begin(), v.end(), show); // apply function show // to each element of vector v

62 Find() Algorithm #include <vector> #include <algorithm>
#include <iostream> int key; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array vector<int>::iterator iter; cout << ”enter value :”; cin >> key; iter=find(v.begin(),v.end(),key); // finds integer key in v if (iter != v.end()) // found the element cout << ”Element ” << key << ” found” << endl; else cout << ”Element ” << key << ” not in vector v” << endl;

63 Find_If() Algorithm #include <vector> #include <algorithm>
#include <iostream> Bool mytest(int n) { return (n>21) && (n <36); }; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array vector<int>::iterator iter; iter=find_if(v.begin(),v.end(),mytest); // finds element in v for which mytest is true if (iter != v.end()) // found the element cout << ”found ” << *iter << endl; else cout << ”not found” << endl;

64 Count_If() Algorithm #include <vector>
#include <algorithm> #include <iostream> Bool mytest(int n) { return (n>14) && (n <36); }; int arr[] = { 12, 3, 17, 8, 34, 56, 9 }; // standard C array vector<int> v(arr, arr+7); // initialize vector with C array int n=count_if(v.begin(),v.end(),mytest); // counts element in v for which mytest is true cout << ”found ” << n << ” elements” << endl;

65 List Container An STL list container is a double linked list, in which
each element contains a pointer to its successor and predecessor. It is possible to add and remove elements from both ends of the list Lists do not allow random access but are efficient to insert new elements and to sort and merge lists

66 List Container int array[5] = {12, 7, 9, 21, 13 };
list<int> li(array,array+5); 12 7 9 21 13 li.push_back(15); li.pop_back(); 13 12 7 9 21 12 7 9 21 15 li.pop_front(); li.push_front(8); 12 8 12 7 9 21 15 7 9 21 li.insert() 19 7 12 17 21 23

67 Insert Iterators If you normally copy elements using the copy algorithm you overwrite the existing contents #include <list> int arr1[]= { 1, 3, 5, 7, 9 }; int arr2[]= { 2, 4, 6, 8, 10 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 copy(l1.begin(), l1.end(), l2.begin()); // copy contents of l1 to l2 overwriting the elements in l2 // l2 = { 1, 3, 5, 7, 9 }

68 Insert Iterators With insert operators you can modify the behavior of the copy algorithm back_inserter : inserts new elements at the end front_inserter : inserts new elements at the beginning inserter : inserts new elements at a specified location #include <list> int arr1[]= { 1, 3, 5, 7, 9 }; int arr2[]= { 2, 4, 6, 8, 10 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 copy(l1.begin(), l1.end(), back_inserter(l2)); // use back_inserter // adds contents of l1 to the end of l2 = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 } copy(l1.begin(), l1.end(), front_inserter(l2)); // use front_inserter // adds contents of l1 to the front of l2 = { 9, 7, 5, 3, 1, 2, 4, 6, 8, 10 } copy(l1.begin(), l1.end, inserter(l2,l2.begin()); // adds contents of l1 at the ”old” beginning of l2 = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }

69 Sort & Merge Sort and merge allow you to sort and merge elements in a container #include <list> int arr1[]= { 6, 4, 9, 1, 7 }; int arr2[]= { 4, 2, 1, 3, 8 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 list<int> l2(arr2, arr2+5); // initialize l2 with arr2 l1.sort(); // l1 = {1, 4, 6, 7, 9} l2.sort(); // l2= {1, 2, 3, 4, 8 } l1.merge(l2); // merges l2 into l1 // l1 = { 1, 1, 2, 3, 4, 4, 6, 7, 8, 9}, l2= {}

70 Functions Objects Some algorithms like sort, merge, accumulate can take a function object as argument. A function object is an object of a template class that has a single member function : the overloaded operator () It is also possible to use user-written functions in place of pre-defined function objects #include <list> #include <functional> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 l1.sort(greater<int>()); // uses function object greater<int> // for sorting in reverse order l1 = { 9, 7, 6, 4, 1 }

71 Function Objects The accumulate algorithm accumulates data over the elements of the containing, for example computing the sum of elements #include <list> #include <functional> #include <numeric> int arr1[]= { 6, 4, 9, 1, 7 }; list<int> l1(arr1, arr1+5); // initialize l1 with arr1 int sum = accumulate(l1.begin(), l1.end() , 0, plus<int>()); int sum = accumulate(l1.begin(), l1.end(),0); // equivalent int fac = accumulate(l1.begin(), l1.end() , 0, times<int>());

72 User Defined Function Objects
class squared _sum // user-defined function object { public: int operator()(int n1, int n2) { return n1+n2*n2; } }; int sq = accumulate(l1.begin(), l1.end() , 0, squared_sum() ); // computes the sum of squares

73 User Defined Function Objects
template <class T> class squared _sum // user-defined function object { public: T operator()(T n1, T n2) { return n1+n2*n2; } }; vector<complex> vc; complex sum_vc; vc.push_back(complex(2,3)); vc.push_back(complex(1,5)); vc.push_back(complex(-2,4)); sum_vc = accumulate(vc.begin(), vc.end() , complex(0,0) , squared_sum<complex>() ); // computes the sum of squares of a vector of complex numbers

74 Associative Containers
In an associative container the items are not arranged in sequence, but usually as a tree structure or a hash table. The main advantage of associative containers is the speed of searching (binary search like in a dictionary) Searching is done using a key which is usually a single value like a number or string The value is an attribute of the objects in the container The STL contains two basic associative containers sets and multisets maps and multimaps

75 Sets and Multisets #include <set>
string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”}; set<string, less<string> > nameSet(names,names+5); // create a set of names in which elements are alphabetically // ordered string is the key and the object itself nameSet.insert(”Patric”); // inserts more names nameSet.insert(”Maria”); nameSet.erase(”Juan”); // removes an element set<string, less<string> >::iterator iter; // set iterator string searchname; cin >> searchname; iter=nameSet.find(searchname); // find matching name in set if (iter == nameSet.end()) // check if iterator points to end of set cout << searchname << ” not in set!” <<endl; else cout << searchname << ” is in set!” <<endl;

76 Set and Multisets string names[] = {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”, ”Maria”, ”Ann”}; set<string, less<string> > nameSet(names,names+7); set<string, less<string> >::iterator iter; // set iterator iter=nameSet.lower_bound(”K”); // set iterator to lower start value ”K” while (iter != nameSet.upper_bound(”Q”)) cout << *iter++ << endl; // displays Lars, Maria, Ole, Patric

77 Maps and Multimaps A map stores pairs <key, value> of a key object and associated value object. The key object contains a key that will be searched for and the value object contains additional data The key could be a string, for example the name of a person and the value could be a number, for example the telephone number of a person

78 Maps and Multimaps #include <map>
string names[]= {”Ole”, ”Hedvig”, ”Juan”, ”Lars”, ”Guido”, ”Patric”, ”Maria”, ”Ann”}; int numbers[]= {75643, 83268, 97353, 87353, 19988, 76455, 77443,12221}; map<string, int, less<string> > phonebook; map<string, int, less<string> >::iterator iter; for (int j=0; j<8; j++) phonebook[names[j]]=numbers[j]; // initialize map phonebook for (iter = phonebook.begin(); iter !=phonebook.end(); iter++) cout << (*iter).first << ” : ” << (*iter).second << endl; cout << ”Lars phone number is ” << phonebook[”Lars”] << endl;


Download ppt "UNIT-V Files."

Similar presentations


Ads by Google