SlideShare a Scribd company logo
1 of 42
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
1. passing file name in constructor at the time of object creation
2. 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) {
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 Exceptionn"; } 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 Exceptionn"; }
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
1. https://www.geeksforgeeks.org/file-handling-c-classes/
2. https://www.startertutorials.com/blog/wp-content/uploads/2016/10/cpp-file-modes.png
3. https://notesformsc.org/cplus-plus-file-pointer-manipulation/
4. https://www.geeksforgeeks.org/exception-handling-c/
5. https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
6. https://www.javatpoint.com/cpp-exception-handling
7. https://www.geeksforgeeks.org/difference-between-n-version-programming-and-recovery-
blocks-techniques/
8. https://cplusplus.com/reference/exception/exception/

More Related Content

Similar to File & Exception Handling in C++.pptx

Similar to File & Exception Handling in C++.pptx (20)

File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
File operations
File operationsFile operations
File operations
 
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
srgoc
srgocsrgoc
srgoc
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++Data File Handiling File POINTERS IN C++
Data File Handiling File POINTERS IN C++
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 

File & Exception Handling in C++.pptx

  • 2. 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
  • 3. 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;
  • 4. 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
  • 5. 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”.
  • 6. Stream Classes for File Operation in C++
  • 7. Stream Classes for File Operation in C++
  • 8. File Operations ● For Using disk file following parameters are necessary. ● Name of the file ● Data type and Structure ● Purpose Opening method
  • 9. 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"; }
  • 10. File Open Methods 1. passing file name in constructor at the time of object creation 2. 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”);
  • 11. File Open Modes : Default Open Modes : ifstream ios::in ofstream ios::out fstream ios::in | ios::out
  • 12. 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
  • 13. 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;
  • 14. 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; }
  • 15. Copy Content from One File to Another Source file original.txt Its Content, ● Try ● File Copy ● Using C++ and getline()
  • 16. 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) {
  • 17. 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; }
  • 18. 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);
  • 19. 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);
  • 20. 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; }
  • 21. 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
  • 23. 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.
  • 24. Sample Program 1 #include <iostream> using namespace std; int main() { int x = -1; cout << "Before try n"; try { cout << "Inside try n";
  • 25. 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)
  • 26. 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); }
  • 27. 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!
  • 28. 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
  • 29. Catch All Block #include <iostream> using namespace std; int main() { try { throw 10; } catch (char *excp) { cout << "Caught " << excp; } catch (...) { cout << "Default Exceptionn"; } 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.
  • 30. #include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "Caught " << x; } catch (...) { cout << "Default Exceptionn"; } return 0; } Output: Default Exception Sample Program 2
  • 31. 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; “.
  • 32. 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
  • 33. 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; }
  • 34. 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”
  • 35. 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 */ }
  • 36. 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.
  • 37. 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 */ }
  • 38. Uncaught Exception in Function Declaration: int main() { try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0; }
  • 40. 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 } }
  • 41. Software fault-tolerance techniques use two common techniques to achieve fault-tolerance. 1. N-version programming : 2. Recovery blocks : Fault-tolerance Techniques
  • 42. REFERENCES 1. https://www.geeksforgeeks.org/file-handling-c-classes/ 2. https://www.startertutorials.com/blog/wp-content/uploads/2016/10/cpp-file-modes.png 3. https://notesformsc.org/cplus-plus-file-pointer-manipulation/ 4. https://www.geeksforgeeks.org/exception-handling-c/ 5. https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm 6. https://www.javatpoint.com/cpp-exception-handling 7. https://www.geeksforgeeks.org/difference-between-n-version-programming-and-recovery- blocks-techniques/ 8. https://cplusplus.com/reference/exception/exception/