0% found this document useful (0 votes)
21 views5 pages

Chapter 6

The document discusses file handling in C++. It explains that a file can be opened using constructors or the open() method. It then provides examples of reading and writing to files, copying contents from one file to another, and counting characters, words, lines, vowels and consonants in a file. It also discusses exceptions, try/catch blocks, and stream classes used for file I/O.

Uploaded by

wednesday262626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

Chapter 6

The document discusses file handling in C++. It explains that a file can be opened using constructors or the open() method. It then provides examples of reading and writing to files, copying contents from one file to another, and counting characters, words, lines, vowels and consonants in a file. It also discusses exceptions, try/catch blocks, and stream classes used for file I/O.

Uploaded by

wednesday262626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Chapter 6:

1. What is file? What are two different ways to open file in C++.
Using constructor & open() function.
->>>a file is a sequence of bytes stored on a storage device, such as a
hard drive or an SSD. A file is a collection of data stored on a computer
or other storage device under a specific name and directory.

Using Constructors:
 ifstream (Input File Stream) Constructor:This constructor is used for reading
from a file.
Ex:ifstream inputFile("example.txt");
 ofstream (Output File Stream) Constructor:This constructor is used for writing
to a file.
Ex: ofstream outputFile("output.txt");

Using open() Method:


 You can also open files using the open() method after constructing the file
stream
object.
 Syntax:
 Stremclass streamobj;
 Stream obj.open(“filename”,mode);
 Example:
 ifstream inputfile;
 inputFile.open("example.txt"); or
 outputFile.open(“example.txt”)
 The open() method allows you to specify additional flags and modes for opening
the
file, providing more flexibility.

2. What are different file operations? Write a C++ program to copy the contents of
one file to
another file.

->>>Operations on Files:
 C++ provides us with four different operations for file handling.
They are:
 open() –This is used to create a file.
 close() – This is used to close the file.
 read() – This is used to read the data from the file.
 write() – This is used to write new data to file.

Write a c++ program copy contents from one file


to another file.

#include<iostream.h>
#include<fstream.h>
#include<string.h>
int main()
{
char ch;
string str;
ifstream in("f1.txt");
ofstream out("f2.txt");
if(in && out)
{
while(in){
in.get(ch);
out.put(ch);
}
cout << "Copy Finished \n";
else{
cerr<<"ERRRR:Files cannot open";
}
in.close();
out.close();
return 0;
}

3. Create a C++ program to read text file content and count number of Characters,
Words and
No.of lines in a text file.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main(){
int noc=0,now=0,nol=0;
char ch;

ifstream f2("f2.txt");

if(!f2){
cerr<<"no such file !";
}

while((ch=f2.get())!=EOF){
if(ch!=' '&&ch!='\n')noc++;
if(ch==' '||ch=='\n')now++;
if(ch=='\n')nol++;
}

f2.close();

cout<<"noc :"<<noc<<endl;
cout<<"now :"<<now<<endl;
cout<<"nol :"<<nol<<endl;

return 0;
}

4. Create a C++ read a text file content and count number of vowels and consonants
in a file.

#include<iostream>
#include<fstream>
#include<cctype>
using namespace std;

int main(){
char ch;
int vowels=0,consonants=0;

ifstream file("f2.txt");
if(!file){
cerr<<"error:no such file";
}

while(file>>ch){
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'){
vowels++;
}else{
consonants++;
}
}
}

file.close();

cout<<"no of v :"<<vowels<<endl;
cout<<"no of cons :"<<consonants<<endl;

return 0;
}

5. What is an exception? How exceptions are handled in C++ with program example
OR Give syntax of Exception handling. Discuss exception handling mechanisms in C++.
In C++, exceptions are runtime anomalies or abnormal
conditions that a program encounters during its execution.
 In C++, an exception is an unexpected or exceptional event that
occurs during the execution of a program and disrupts the normal
flow of control.
 The process of handling these exceptions is called exception
handling.
 Exception Handling in C++ is a process to handle runtime
errors.
 std::exception is an exception and parent class of all standard
C++ exceptions.
1. try
The try block is used to place the code that may occur exception.
The try keyword represents a block of code that may throw an exception placed
inside
the try block. It’s followed by one or more catch blocks. If an exception occurs,
try
block throws that exception.
Eg: try{ }
2. catch
The catch block is used to handle the exception thrown by the throw keyword.
The catch statement represents a block of code that is executed when a particular
exception is thrown from the try block. The code to handle the exception is written
inside the catch block.
Eg: Catch(Exception e)
3. throw
The throw block throws an exception when an error is detected. The throw statement
is used to manually throw an exception.
When a program encounters a throw statement, then it immediately terminates the
current function and starts finding a matching catch block to handle the thrown
exception.
Eg: throw MyException("An error occurred!");
 Syntax for Exception Handling in C++
try {
// code that may raise an exception
throw argument;
}
catch (exception)
{
// code to handle exception
}
Catch(...)
{
// code to handle unexpected exception
}

6. Write a C++ program to demonstrate usage of try, catch and throw to handle
exception.
#include <iostream>
using namespace std;
int main()
{
double a=10, b, arr[3];
int index;
cout << "Enter array index: ";
cin >> index;
try
{
if (index >= 3)
{ throw "Error: Array out of bounds!"; // throw
exception if array out of bounds
}
cout << "Enter b value: ";
cin >> b;

if (b == 0)
throw 0; // throw exception if denominator is 0
{ arr[index] = a / b;
cout << arr[index] << endl;
}
}
// catch "Array out of bounds" exception
catch (const char * msg)
{ cout << msg << endl;
}
// catch "Divide by 0" exception
catch (int num)
{ cout << "Error: Cannot divide by " << num << endl;
}
// catch any other exception or generic expection
catch (...)
{
cout << "Unexpected exception!" << endl;
}
return 0;
}

7. What is stream ? explain stream class hierarchy used for file handling in detail
.

Stream: a stream refers to a sequence of characters that are transferred between


the
program and input/output (I/O) devices. Stream is the sequence of bytes or flow of
data.
Classes for file stream operations
The ios class is a base class for several other classes that are used in handling
I/O operations.
1.istream: stands for input stream.
This class is derived from ios and provides functionalities for input streams.
ifstream: ifstream is an input file stream.
 This is derived from istream and is specifically designed for input from files.
2.ostream: stands for output stream.
This class is derived from ios and provides functionalities for output streams.
ofstream: ofstream is an output file stream.
 This is derived from ostream and is specifically designed for output to files.
3. iostream: stands for input output stream
This class is derived from both istream and ostream, providing functionalities for
both input and
output streams.
4.streambuf: This class is responsible for managing the buffer, which is used for
reading from or
writing to a device. It is derived from ios_base.
 filebuf: This class is derived from streambuf and is used for reading from or
writing to files.
 stringbuf: This class is derived from streambuf and is used for reading from or
writing to strings.
5.fstream:This class is the combination of both of ofstream and ifstream.
It provides the capability of creating, writing and reading a file.

You might also like