Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views17 pages

C++ Unit 5

The document provides an overview of file handling in C++, detailing the use of the fstream library, which includes classes for reading and writing files. It explains file operations such as opening, reading, writing, and closing files, along with examples of code for each operation. Additionally, it briefly covers exception handling in C++, including the use of try, catch, and throw keywords, as well as standard exceptions.

Uploaded by

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

C++ Unit 5

The document provides an overview of file handling in C++, detailing the use of the fstream library, which includes classes for reading and writing files. It explains file operations such as opening, reading, writing, and closing files, along with examples of code for each operation. Additionally, it briefly covers exception handling in C++, including the use of try, catch, and throw keywords, as well as standard exceptions.

Uploaded by

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

C++ Files and Streams

File Handling in C++ | How to


Open, Read and Close
 What is File Handling in C++?
 fstream library
 ofstream
 ifstream
 fstream
 File Operations in C++
 Opening files in C++
 Writing to file
 Reading from file in C++
 inFile C++
 Closing a file in C++
 File Position Pointers

What is file handling in C++?


Files store data permanently in a storage device. With file handling, the
output from a program can be stored in a file. Various operations can be
performed on the data while in the file.

A stream is an abstraction of a device where input/output operations


are performed. You can represent a stream as either a destination or a
source of characters of indefinite length. This will be determined by
their usage. C++ provides you with a library that comes with methods
for file handling. Let us discuss it.

The fstream Library


The fstream library provides C++ programmers with three classes for
working with files. These classes include:
 ofstream– This class represents an output stream. It’s used for
creating files and writing information to files.
 ifstream– This class represents an input stream. It’s used for
reading information from data files.
 fstream– This class generally represents a file stream. It comes
with ofstream/ifstream capabilities. This means it’s capable of
creating files, writing to files, reading from data files.
Now, This topic of file handling is further divided into sub-topics:

 Create a file
 Open a file
 Read from a file
 Write to a file
 Close a file
File Operations in C++
C++ provides us with four different operations for file handling. They are:

1. open() – This is used to create a file.


2. read() – This is used to read the data from the file.
3. write() – This is used to write new data to file.
4. close() – This is used to close the file.
We will look into each of these and try to understand them better.

Opening files in C++

To read or enter data to a file, we need to open it first. This can be


performed with the help of ‘ifstream’ for reading and ‘fstream’ or
‘ofstream’ for writing or appending to the file. All these three objects have
open() function pre-built in them.

Syntax:

1 open( FileName , Mode );


Here:

FileName – It denotes the name of file which has to be opened.

FILE MODES
Mode – There different mode to open a file and it explained in this article.
Mode Description

iso::in File opened in reading mode

iso::out File opened in write mode

iso::app File opened in append mode

File opened in append mode but read and write performed at the
iso::ate
end of the file.

iso::binary File opened in binary mode

iso::trunc File opened in truncate mode

iso::nocreate The file opens only if it exists

iso::noreplace The file opens only if it doesn’t exist

In C++, we can use two modes simultaneously with the help of | (OR)
operator.

Program for Opening File:

1 #include<iostream>
2 #include<fstream>
3 using namespace std;
4 int main(){
5 fstream FileName;
6 FileName.open("FileName", ios::out);
7 if (!FileName){
8
cout<<"Error while creating the file";
9
}
1
0 else{

1 cout<<"File created successfully";


1
1
2
1
3 FileName.close();
1 }
4
return 0;
1
5 }
Explanation of above code

1. Here we have an iostream library, which is responsible for


input/output stream.
2. We also have a fstream library, which is responsible for handling
files.
3. Creating an object of the fstream class and named it as
‘FileName’.
4. On the above-created object, we have to apply the open()
function to create a new file, and the mode is set to ‘out’ which
will allow us to write into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. We use the close() function on the object to close the file.
Output

File created successfully

Writing to File

Till now, we learned how to create the file using C++. Now, we will learn
how to write data to file which we created before. We will use fstream or
ofstream object to write data into the file and to do so; we will use stream
insertion operator (<<) along with the text enclosed within the double-
quotes.

With the help of open() function, we will create a new file named
‘FileName’ and then we will set the mode to ‘ios::out’ as we have to write
the data to file.

Syntax:

1 FileName<<"Insert the text here";


Program for Writing to File:

1 #include<iostream>
2 #include<fstream>
3
4
5
6 using namespace std;
7 int main() {
8
fstream FileName;
9
FileName.open("FileName.txt", ios::out);
1
0
if (!FileName) {

1 cout<<" Error while creating the file ";


1 }
1 else {
2
cout<<"File created and data got written to file";
1
3 FileName<<"This is a blog posted on <a href="https://www.
Learning Homepage" target="_blank" rel="noopener">Great Learning</a>";
1
4 FileName.close();
1 }
5
return 0;
1
6 }
Explanation of above code

1. Here we have an iostream library, which is responsible for


input/output stream.
2. We also have a fstream library, which is responsible for handling
files.
3. Creating an object of the fstream class and named it as
‘FileName’.
4. On the above-created object, we have to apply the open()
function to create a new file, and the mode is set to ‘out’ which
will allow us to write into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. Writing the data to the created file.
9. We use the close() function on the object to close the file.
Output

File created and data got written to file

Reading from file in C++

Getting the data from the file is an essential thing to perform because
without getting the data, we cannot perform any task. But don’t worry, C+
+ provides that option too. We can perform the reading of data from a file
with the CIN to get data from the user, but then we use CIN to take inputs
from the user’s standard console. Here we will use fstream or ifstream.

Syntax:

1 FileName>>Variable;
Content of FileName.txt:

Hello World, Thank You for Visiting Great Learning.

Program for Reading from File:

1 #include<iostream>
2 #include <fstream>
3 using namespace std;
4 int main() {
5 fstream FileName;
6 FileName.open("FileName.txt", ios::in);
7 if (!FileName) {
8
cout<<"File doesn’t exist.";
9
}
1
0 else {

1 char x;
1 while (1) {
1 FileName>>x;
2
if(FileName.eof())
1
3 break;
1 cout<<x;
4
}
1
5 }
1 FileName.close();
6
return 0;
1
7 }
1
8
1
9
2
0
2
1
Explanation of above code

1. Here we have an iostream library, which is responsible for


input/output stream.
2. We also have a fstream library which is responsible for handling
files.
3. Creating an object of the fstream class and named it ‘FileName’.
4. On the above-created object, we have to apply the open()
function to create a new file, and the mode is set to ‘in’ which
will allow us to read from the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Creating a character(char) variable with the named x.
8. Iterating of the file with the help of while loop.
9. Getting the file data to the variable x.
10. Here we are using if condition with eof() which stands for
the end of the file to tell the compiler to read till the file’s end.
11. We use the ‘break’ statement to stop the reading from file
when it reaches the end.
12. The print statement to print the content that is available in
the variable x.
13. We use the close() function on the object to close the file
Output

Hello World, Thank You for Visiting Great Learning.

Infile C++

We can also use inFile to read from the file. Here, inFile >> S takes in
the file stream, which is your file data, and uses a space delimiter (breaks
it up by whitespace) and then puts the contents in the variable S.

Example:

If we had a file that had the data:

“My Cat is Hungry”

and we used inFile >> S here, i.e.:

1ifstream inFile("file.txt")
2string words;
3while(inFile >> words) {
4 cout << words << endl;
5}
We will get the output:

My

Cat

is

Hungry

The inFile >> words will continue to return ‘true’ until there are no more
items separated by whitespace.

Closing a file in C++

Closing a file is a good practice, and it is must to close the file. Whenever
the C++ program comes to an end, it clears the allocated memory, and it
closes the file. We can perform the task with the help of close() function.

Syntax:

1 FileName.close();
Program to Close a File:

1 #include <iostream>
2 #include <fstream>
3 using namespace std;
4 int main() {
5 fstream FileName;
6 FileName.open("FileName.txt", ios::in);
7 if (!FileName) {
8
cout<<"File doesn’t exist";
9
}
1
0 else {

1 cout<<"File opened successfully";


1 }
1 }
2
FileName.close();
1
3 return 0;
1
4
1
5
1
6 }
Explanation of above code

1. Here we have an iostream library, which is responsible for


input/output stream.
2. We also have a fstream library, which is responsible for handling
files.
3. Creating an object of the fstream class and named it as
‘FileName’.
4. On the above-created object, we will apply the open() function to
create a new file, and the mode is set to ‘out’ which allows us to
write into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file opened or not.
8. We use the close() function on the object to close the file.
File Position Pointers

We can reposition the file-position pointer in istream and ostream using its
special member functions. These member functions are ‘seekg’ and
‘seekp’. ‘seekg’ or ‘seek get’ is used for istream and ‘seekp’ or ‘seek put’
is used for ostream.

Both these member functions take long integer as arguments. A second


argument is used to specify the direction of seek. The seek directions can
be ios::beg( for positioning in the beginning of a stream), ios::cur( for
positioning relative to a current position of a stream) and ios::end( to
position relative to the end of a stream).

This brings us to the end of the blog on the concept of File Handling in C+
+. We hope that you found this comprehensive and helpful and were able
to gain the required knowledge.

C++ Exception Handling


An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
catch − A program catches an exception with an exception handler at the

place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions
in case your try block raises more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.

Following is an example of throwing an exception when dividing by zero condition


occurs −

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to
specify that a catch block should handle any type of exception that is thrown in a
try block, you must put an ellipsis, ..., between the parentheses enclosing the
exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we


catch it in catch block.

Live Demo

#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

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;
}
Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run above
code, this would produce the following result −
Division by zero condition!
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception> which we can
use in our programs. These are arranged in a parent-child class hierarchy shown
below −
Here is the small description of each exception mentioned in the above hierarchy –

Sr.No Exception & Description

1 std::exception
An exception and parent class of all the standard C++ exceptions.

2 std::bad_alloc
This can be thrown by new.

3 std::bad_cast
This can be thrown by dynamic_cast.

4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.

5 std::bad_typeid
This can be thrown by typeid.

6 std::logic_error
An exception that theoretically can be detected by reading the code.

std::domain_error
7 This is an exception thrown when a mathematically invalid domain is
used.

8 std::invalid_argument
This is thrown due to invalid arguments.

9 std::length_error
This is thrown when a too big std::string is created.

std::out_of_range
10 This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().

11 std::runtime_error
An exception that theoretically cannot be detected by reading the code.

12 std::overflow_error
This is thrown if a mathematical overflow occurs.

13 std::range_error
This is occurred when you try to store a value which is out of range.

14 std::underflow_error
This is thrown if a mathematical underflow occurs.
Define New Exceptions
You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way −
Live Demo

#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception {


const char * what () const throw () {
return "C++ Exception";
}
};
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}

This would produce the following result −

MyException caught
C++ Exception

What is a Sequential File?


A sequential file is a type of file structure used in computer systems to organize and store data in a
sequential order. In a sequential file, records are stored one after another, with each new record being
appended to the end of the file. This means that the records are stored in the order they are added, and
accessing the data follows a sequential pattern from the beginning to the end of the file.
In a sequential file, the records have a fixed length or are variable-length with a marker indicating the
end of each record. When reading or writing data in a sequential file, the file pointer moves
sequentially through the file, starting from the first record and progressing through each subsequent
record.

What is a Random Access File?


A random access file is a type of file structure that allows direct access to any record within the file,
enabling efficient searching, updating, and retrieval of individual records. Unlike sequential access
files where data is organized and accessed sequentially, random access files provide the ability to
access records in any order based on their position or key.
In a random access file, records are stored with a unique identifier or a specific position within the
file. This identifier or position allows for direct access to a particular record without the need to
traverse through the entire file. The file system maintains an index or data structure that facilitates
efficient retrieval of records based on their identifiers or positions.
Random access files are advantageous in scenarios where frequent direct access or modification of
specific records is required. They are commonly used in applications that involve searching for
specific data, updating specific records, or retrieving data based on specific criteria. Examples of
applications that benefit from random access files include databases, file systems, and data storage
systems.
Difference Between C++ Text File and Binary File
 Read
 Discuss
 Courses

 Practice

A text file is the one in which data is stored in the form of ASCII characters and is normally used for
storing a stream of characters. Text files are organized around lines, each of which ends with a
newline character (‘\n’). The source code files are themselves text files.
A binary file is the one in which data is stored in the file in the same way as it is stored in the main
memory for processing. It is stored in binary format instead of ASCII characters. It is normally used
for storing numeric information (int, float, double). Normally a binary file can be created only from
within a program and its contents can be read only by a program.
Text File vs Binary File
The following are some of the differences between text files and binary files.

S.
No. Text file Binary File

Binary files cannot easily be transferred from one


computer system to another due to variations in
The text files can easily be transferred from
1. the internal variations in the internal
one computer system to another.
representation which varies from computer to
computer.

It stores data using ASCII format i.e. human- It stores data in binary format i.e. with the help of
2.
readable graphic characters. 0 and 1.

3. These files are easily readable and modifiable These files are not easily readable and modifiable
because the content written in text files is because the content written in binary files is not
S.
No. Text file Binary File

human readable.
Content written in binary files is not human- human-readable and it is encrypted content.
readable and looks like encrypted content.

4. These files create portability problems. These files are easily portable.

Text files save the data by converting each


digit in data into ASCII format which will take
These save memory because the data of any type
up much of the space as compared to the
will get stored in memory as per its memory size.
required one.
5. For example, any integer number irrespective of
For example, the number 546378 is an integer
individual digits in the number will be stored by
that should occupy 4 bytes in the disk but it
consuming 4 bytes.
will occupy 6 bytes, 1 byte for each digit in the
number.

The ios:: binary mode has to be used with binary


6. Any file is by default text file.
files while opening them.

Error in a textual file can be easily recognized Error in a binary file corrupts the file and is not
7.
and eliminated. easily detected.

In a text file, a new line character is first


converted to a carriage return-line feed
In binary file, no such conversion from newline to
8. combination and then written to the disk. Vice
carriage return-line feed combination is done.
versa happens when a line is read from the text
file.

In a text file, a special character with ASCII


code 26 is inserted at the end of the file. This There is no such special character in the binary
9.
character signals the EOF to the program when file to signal EOF.
encountered.

Text files are used to store data more user


10. Binary files are used to store data more compactly.
friendly.

Mostly .txt and .rtf are used as extensions to


11. Can have any application defined extension.
text files.

 C++

#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream FileName;
FileName.open("FileName.txt", ios::out);
if (!FileName) {
cout<<" Error while creating the file ";
}

else {
cout<<"File created and data got written to file";
FileName<<"This is a blog posted on Great Learning";
FileName.close() ;}

return 0 ;
}

You might also like