0% found this document useful (0 votes)
38 views35 pages

File Handling

The document provides an overview of file handling in C++, detailing the importance of files for managing large data collections. It explains key concepts such as streams, file operations (create, open, read, write, close), and the use of classes like ifstream, ofstream, and fstream for file manipulation. Additionally, it covers different file types (ASCII text and binary) and includes sample programs demonstrating file operations.

Uploaded by

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

File Handling

The document provides an overview of file handling in C++, detailing the importance of files for managing large data collections. It explains key concepts such as streams, file operations (create, open, read, write, close), and the use of classes like ifstream, ofstream, and fstream for file manipulation. Additionally, it covers different file types (ASCII text and binary) and includes sample programs demonstrating file operations.

Uploaded by

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

Object Oriented Programming

(24ECE2101)

Batch 2024, ECE

Teaching Team

Dr Deepti Prit Kaur Dr Meenu Garg


Group X Group Y
File Handling
INTRODUCTION

• A file is a collection of data stored on a secondary storage device


like hard disk.
• File is basically used because real-life applications involve large
amounts of data.

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
STREAMS IN C++

• A stream is a logical interface to the devices that are connected


to the computer.
• 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.
• In C++, the standard streams are termed as pre-connected input
and output channels between a text terminal and the program
(when it begins execution).
• The three standard streams in C++ language are:
- console input (cin)
- console output (cout), and
- console error (cerr).
Standard Streams
Console input ( cin ) or standard input ( stdin )
• Standard input is the stream from which the program receives its
data.
• The program requests transfer of data using the read operation.
Console output ( cout ) or standard output ( stdout )
• Standard output is the stream where a program writes its output
data.
• Streambuf is a pointer which points to the buffer which is used to
manage the input and output streams.
Console error ( cerr ) or standard error ( stderr )
• Standard error is basically an output stream used by programs to
report error messages or diagnostics.
• Console log ( clog ) :It is a fully buffered version of cerr .clog which is
mainly used to report problems.
CLASSES FOR FILE STREAM OPERATIONS
CLASSES FOR FILE STREAM OPERATIONS

• The I/O system of C++ contains a set of classes which define the
file handling methods. These include ifstream, ofstream and
fstream classes.
• ifstream , ofstream , and fstream are derived from fstream base
and from iostream.h .
• Classes that manage the disk files are declared in fstream.h .
Therefore, fstream.h must be included in any program that uses
files.
• Filebuf: It is used to set the file buffer for read and write
operations.
• fstream base: It provides functions common to the file streams.
It provides functions for both input and output operations. This
file is the base class for: ifstream , ofstream , and fstream , and
contains open() and close() as its members.
CLASSES FOR FILE STREAM OPERATIONS

• ifstream: We use this class to read data from files. It provides


functions for data input. Therefore, the open() defined as its
member opens a stream in the input mode by default. Moreover,
ifstream inherits functions such as get() , getline() ,read(), seekg(),
and tellg() functions from the istream class.
• ofstream: This class helps create and write the data to the file
obtained from the program’s output. It provides functions for
data output. Therefore, the open() defined as its member, opens
a stream in the output mode by default. Moreover, ofstream
inherits functions like put() , write() ,seekp() , and tellp() functions
from the ostream class.
• fstream: This class is the combination of both ofstream and
ifstream. It provides the capability of creating, writing and
reading a file.
CLASSES FOR FILE STREAM OPERATIONS

To access these classes, we must include the fstream as a


header file like how we declare iostream in the header.
Types of files

• ASCII Text File


• Binary File
ASCII Text Files

• A text file is a stream of characters that can be sequentially


processed by a computer in forward direction. Hence, a text file is
usually opened for only one kind of operation such as reading,
writing or appending at any given time.
• As text files only process characters, they can only read or write
data one character at a time in a line.
• A text file is not a C++ string and is not terminated by a null
character.
• When a text file is used, there are actually two representations of
data—internal or external.
• For example, an int value will be represented as two or four bytes
of memory internally but externally, the int value will be
represented as a string of characters representing its decimal or
hexadecimal values.
Binary Files

• A binary file is a file which may contain any type of data, encoded in binary
form for computer storage and processing purposes. A binary file is a
collection of bytes.
• A binary file does not require any special processing of the data and each byte
of data is transferred to or from the disk unprocessed.
• C++ places no constructs on the file and it may be read from, or written to, in
any manner the programmer wants.
• While text files can be processed sequentially, binary files, on the other
hand, can be either processed sequentially or randomly depending on the
needs of the application.
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.close() – This is used to close the file.

3.read() – This is used to read the data from the file.

4.write() – This is used to write new data to file.


Opening a File
In order to work with files, we first need to open them. In C++, we
can open a file using the ofstream and ifstream classes.

For example, here's how we can open a file using ofstream:


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.

Here:
FileName – It denotes the name of file which has to be opened.
Mode – There different mode to open a file which are explained
in next part.
File Modes

In C++, we can
use two modes
simultaneously
with the help of
| (OR) operator.
Sample Program 1
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.
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.
Sample Program 2
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.
Sample Program 3
OPENING AND CLOSING OF FILES

• Before we perform I/O operations on a file, the file must be


first opened to get a handle. The file handle serves as a
pointer to the file. However, to obtain this handle, the user
must specify the name of the file, data type, purpose, and
the opening method.
• The data type and the structure of the file stream is defined
using stream classes; ifstream , ofstream , or fstream ,
depending on the purpose of its usage, depending on
whether the file is being opened for reading data or writing.
• For example, if we know that we are opening the file only to
read data, the data type of the file can be ifstream .
OPENING AND CLOSING OF FILES

• If we are opening for writing data, the file must be opened


using ofstream class.
• If the file is being opened for simultaneous read and write
operations, then it must be opened using fstream class.
• We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
Opening Files using Constructors

1. Create a file stream object. For example, ofstream is used to create the output
stream and ifstream is used to create the input stream.
2. Initialize the file stream object by specifying the file name.
Implementation of Opening Files using
Constructors
Opening Files using Member function

• A file can also be opened explicitly by using open() , defined


as member function of the class
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.
Sample Program 4
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.
Basic File Operations

1.Creating and Opening Files: You can create a file


using ofstream for writing or ifstream for reading.

2.Closing Files: Always close a file after performing


operations using the .close() method.

3.Checking File Status: You can use


the .is_open() method to check if a file is open
successfully.
Writing 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.

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.
Sample Program 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 ‘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
Reading from file

34
Thanks

You might also like