File & Exception Handling in C++.pptx

RutujaTandalwade 377 views 42 slides Oct 22, 2023
Slide 1
Slide 1 of 42
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42

About This Presentation

oops


Slide Content

File Handling in C++

File Handling in C++ File handling is used for store a data permanently in computer. Using file handling we can store our data in secondary memory (Hard disk). How to achieve the File Handling For achieving file handling we need to follow the following steps:- STEP 1-Naming a file / Create a file STEP 2-Opening a file STEP 3-Writing data into the file STEP 4-Reading data from the file STEP 5-Closing a file

Program Write into file and read data from file #include<iostream> #include<fstream> using namespace std; int main() {     int rno , fee;     char name[50];     cout <<"Enter the Roll Number:";     cin >> rno ;       cout <<"\ nEnter the Name:";     cin >>name;     cout <<"\ nEnter the Fee:";     cin >>fee;

    ofstream fout ("student.doc"); //"d:/student.doc"     fout << rno <<"\t"<<name<<"\t"<<fee; //write data to the file student     fout.close ();     ifstream fin("student.doc");     fin>> rno >>name>>fee; //read data from the file student     fin.close ();     cout << endl << rno <<"\t"<<name<<"\t"<<fee;     return 0; } Program Write into file and read data from file

Streams in C++ :- The sequence of bytes given as input to the executing program and the sequence of bytes that comes as output from the executing program are called stream. In other words, streams are nothing but the flow of data in a sequence. The input and output operation between the executing program and the devices like keyboard and monitor are known as “ console I/O operation ”. The input and output operation between the executing program and files are known as “ disk I/O operation ”.

Stream Classes for File Operation in C++

Stream Classes for File Operation in C++

File Operations For Using disk file following parameters are necessary. Name of the file Data type and Structure Purpose Opening method

Sample Program 1: To Create and Write a File #include <iostream> #include <fstream> using namespace std; int main() { ofstream MyFile("filename.txt"); // Create and open a text file // Write to the file MyFile << "Files can be tricky, but it is fun enough!"<< endl; MyFile.close(); // Close the file cout<<"Successful"; }

File Open Methods passing file name in constructor at the time of object creation using the open( ) method Open File by using constructor ifstream (const char* filename, ios_base::openmode mode = ios_base::in); ifstream fin(filename, openmode) by default openmode = ios::in ifstream fin(“filename”); Open File by using open method Calling of default constructor ifstream fin; fin.open(filename, openmode) fin.open(“filename”);

File Open Modes : Default Open Modes : ifstream ios::in ofstream ios::out fstream ios::in | ios::out

Sample Program to write and read using ifstream & ofstream classes /* File Handling with C++ using ifstream & ofstream class object*/ /* To write the Content in File Then to read the content of file*/ #include <iostream> #include <fstream> using namespace std; int main() { ofstream fout; // Creation of ofstream class object

Sample Program to write and read using ifstream & ofstream classes 2 string line; /* by default ios::out mode, automatically deletes the content of file. To append the content, open in ios:app fout.open("sample.txt", ios::app) */ fout.open("sample.txt"); while (fout) { // Execute a loop If file successfully opened // Read a Line from standard input getline(cin, line); // Press -1 to exit if (line == "-1") break; fout << line << endl; // Write line in file } // Close the File fout.close(); cout<<"File created" <<endl;

Sample Program to write and read using ifstream & ofstream classes 3 // Creation of ifstream class object to read the file ifstream fin; fin.open("sample.txt"); // by default open mode = ios::in mode while (fin) { // Execute a loop until EOF (End of File) getline(fin, line); // Read a Line from File cout << line << endl; // Print line in Console } fin.close(); // Close the file return 0; }

Copy Content from One File to Another Source file original.txt Its Content, Try File Copy Using C++ and getline ()

Copy Content from One File to Another // C++ Program to demonstrate copying the content of a .txt file #include < fstream > #include <iostream> using namespace std; int main() {     string line;     // For writing text file Creating ofstream & ifstream class object     ifstream ini_file ( "original.txt“); // This is the original file     ofstream out_file ( "copy.txt" );     if ( ini_file && out_file ) {         while ( getline ( ini_file , line)) {             out_file << line << "\n";         }         cout << "Copy Finished \n";     }     else {         // Something went wrong         printf ("Cannot read File");     }     // Closing file     ini_file.close ();     out_file.close ();     return 0; }

Copy Content from One File to Another if ( ini_file && out_file ) {         while ( getline ( ini_file , line)) {             out_file << line << "\n";         }         cout << "Copy Finished \n";     }     else {         // Something went wrong         printf ("Cannot read File");     }     // Closing file     ini_file.close ();     out_file.close ();     return 0; }

Copy Content from One File to Another Example 2: // C++ to demonstrate copying the contents of one file into another file #include <bits/ stdc ++.h> using namespace std; int main() {     fstream f1, f2;     string ch ;     // opening first file to read the content     f1.open("original.txt", ios ::in);     // opening second file to write the content copied from first file     f2.open("file2.txt", ios ::out);

Copy Content from One File to Another Example 2: while (!f1.eof()) {     // extracting the content of first file line by line         getline (f1, ch );   // writing content to second file line by line         f2 << ch << endl ;     }     // closing the files     f1.close();     f2.close();     // opening second file to read the content     f2.open("file2.txt", ios ::in);    

Copy Content from One File to Another Example 2: while (!f2.eof()) {   // extracting the content of second file line by line         getline (f2, ch );   // displaying content         cout << ch << endl ;     }     // closing file     f2.close();     return 0; }    

File Pointers A pointer is used to handle and keep track of the files being accessed. Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in output mode file), which tells the current position where reading or writing will take place with the use of opening modes and their respective manipulators. seekg(int offset, reference_position) seekp(int offset, reference_position) Syntax

Exception Handling in C++

Exception Handling in C++ Exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a) Synchronous , b) Asynchronous (i.e., exceptions which are beyond the program’s control, such as disc failure, keyboard interrupts etc.). C++ provides the following specialized keywords for this purpose: try : Represents a block of code that can throw an exception. catch : Represents a block of code that is executed when a particular exception is thrown. throw : Used to throw an exception. Also used to list the exceptions that a function throws but doesn’t handle itself.

Sample Program 1 #include <iostream> using namespace std; int main() { int x = -1; cout << "Before try \n"; try { cout << "Inside try \n";

Sample Program 1 if (x < 0) { throw x; cout << "After throw (Never executed) \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch (Will be executed) \n"; return 0; } OUTPUT: Before try Inside try Exception Caught After catch (Will be executed)

Sample Program 2 : Division by 0 Exception #include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); }

Sample Program 2 : Division by 0 Exception int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; } catch (const char* msg) { cerr << msg << endl; } return 0; } OUTPUT: Division by zero condition!

Why Exception Handling? 1) Separation of Error Handling code from Normal Code 2) Functions/Methods can handle only the exceptions they choose 3) Grouping of Error Types Exception Handling Mechanism

Catch All Block #include <iostream> using namespace std; int main() { try { throw 10; } catch (char *excp) { cout << "Caught " << excp; } catch (...) { cout << "Default Exception\n"; } return 0; } There is a special catch block called the ‘catch all’ block, written as catch(…), that can be used to catch all types of exceptions.

#include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "Caught " << x; } catch (...) { cout << "Default Exception\n"; } return 0; } Output: Default Exception Sample Program 2

Nested Try Block #include <iostream> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "Handle Partially "; throw; // Re-throwing an exception } } catch (int n) { cout << "\nHandle remaining "; } return 0; } In C++, try/catch blocks can be nested. Also, an exception can be re-thrown using “throw; “.

Exception, Constructor, Destructor #include <iostream> using namespace std; class Test { public:     Test() { cout << "Constructor of Test " << endl ; }     ~Test() { cout << "Destructor of Test " << endl ; } }; int main() {     try {         Test t1;         throw 10;     }     catch (int i ) {         cout << "Caught " << i << endl ;     } return 0; } OUTPUT: Constructor of Test Destructor of Test Caught 10

Base and derived classes as an exception in C++ // C++ Program to demonstrate a catching of Derived exception and printing it successfully #include <iostream> using namespace std; class Base {}; class Derived : public Base {}; int main() { Derived d; try { // Monitored code throw d; }

Base and derived classes as an exception in C++ catch (Derived d) { cout << "Caught Derived Exception"; } catch (Base b) { cout << "Caught Base Exception"; } return 0; } If both base and derived classes are caught as exceptions, then the catch block of the derived class must appear before the base class. If we put the base class first then the derived class catch block will never be reached. Program prints “Caught Derived Exception”

Uncaught Exception in Function Declaration #include <iostream> using namespace std; // This function signature is fine by the compiler, but not recommended. // Ideally, the function should specify all uncaught exceptions and function // signature should be "void fun(int *ptr, int x) throw (int *, int)" void fun(int *ptr, int x) { if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */ }

Uncaught Exception in Function Declaration int main() { try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0; } Unlike Java, in C++, all exceptions are unchecked, i.e., the compiler doesn’t check whether an exception is caught or not. So, it is not necessary to specify all uncaught exceptions in a function declaration. Although it’s a recommended practice to do so.

Uncaught Exception in Function Declaration: #include <iostream> using namespace std; // Here we specify the exceptions that this function throws. void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception specification { if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */ }

Uncaught Exception in Function Declaration: int main() { try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0; }

C++ Standard Exceptions

Define New Exceptions #include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception" ; } }; int main() { try { throw MyException (); } You can define your own exceptions by inheriting and overriding exception class functionality. use std::exception class to implement your own exception in standard way Here, what() is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception. catch ( MyException & e) { std:: cout << " MyException caught" << std:: endl ; std:: cout << e.what () << std:: endl ; } catch (std:: exception & e) { //Other errors } }

Software fault-tolerance techniques use two common techniques to achieve fault-tolerance. 1. N-version programming : 2. Recovery blocks : Fault-tolerance Techniques

REFERENCES https://www.geeksforgeeks.org/file-handling-c-classes/ https://www.startertutorials.com/blog/wp-content/uploads/2016/10/cpp-file-modes.png https://notesformsc.org/cplus-plus-file-pointer-manipulation/ https://www.geeksforgeeks.org/exception-handling-c/ https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm https://www.javatpoint.com/cpp-exception-handling https://www.geeksforgeeks.org/difference-between-n-version-programming-and-recovery-blocks-techniques/ https://cplusplus.com/reference/exception/exception/
Tags