Week 5 - Exception, Error and Files
Week 5 - Exception, Error and Files
Without proper input validation, the program might behave unpredictably, leading to runtime
errors or security vulnerabilities.
Exception handling simplifies input validation by catching and managing errors when invalid
data is entered.
C++ provides file handling through the <fstream> library, which includes three primary classes:
#include <fstream>
int main() {
if (outFile.is_open()) {
} else {
return 0;
What is ios?
• ios stands for input/output stream, a base class in C++ that defines constants (flags) for
file operations.
• The ios namespace provides several flags that specify how a file should be opened or
operated on.
1. ios::in
o Opens the file for input (reading).
o Without this flag, reading operations like getline() or >> would fail.
2. ios::out
o Opens the file for output (writing).
o If the file does not exist, it is created.
o By itself, this flag overwrites the content of the file, but when combined with
ios::app, it preserves the content and appends new data.
3. ios::app
o Opens the file in append mode, which positions the file pointer at the end of the
file.
o Writing operations will always add content at the end of the file, preserving the
existing content.
5. Error Handling in File Operations
It’s essential to handle errors, such as:
• File not found.
• Insufficient permissions.
• End of file reached.
Common Methods:
1. is_open(): Checks if the file is successfully opened.
2. eof(): Checks if the end of the file is reached.
3. fail(): Indicates a logical error in file operations.
Hands-On Activities
1. Write a program to save user details (name, age, email) to a file.
2. Read the saved details from the file and display them.
3. Implement a basic text editor that can read from and write to a file.