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

Chapter Four-File Processing v1.0

Uploaded by

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

Chapter Four-File Processing v1.0

Uploaded by

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

Chapter Four: File

processing
Files and Streams

▪ Files are used to store large amounts of data in the


secondary storage devices such as hard drives, optical
disks, tapes, and so forth. We store data in variables
and arrays, but they are temporary or non-persistent. To
store persistent data, we generally use two types of file
structures: flat files (unordered) or databases (ordered).
Data stored in a database are naturally ordered due to
the complicated logic applied to its storage and retrieval
policy. In most cases, a data manager keeps watch on
them.
What is a Data Item?

▪ At the core, data items are


reduced to a combination of
bits represented by zeros
and ones. The smallest unit
of data item designated by
data type, char, occupies
one byte of memory.
▪ when we store ‘A’, we are
actually storing 65
(01000001 in binary,
according to the ASCII
character set).
Files and Streams

▪ In C++ file processing, files are nothing but a sequence


of bytes without any structure. A file either ends with a
specific byte number or with a marker called EOF (end-
of-file).
▪ As we open a file, an object is created. This object is
associated with a stream. This stream provides the
communicating channel between the program and the
file. The cin (standard input) and cout (standard output)
objects that we commonly use in C++ are nothing but
the objects that open up the channel for input
streaming from the keyboard and output streaming to
the screen, respectively.
Streams in C++

▪ The most common stream objects in C++ are: cin,


cout, cerr, and clog. These objects are created as we
include the iostream header into a program. The cin
object associates with the standard input stream, cout
with the standard output stream, and cerr and clog with
the standard error stream. Note that the standard input
or output stream does not always mean keyboard and
screen/monitor. It can be any device that pertains to
input or output such as touch screen devices. The error
streams typically associate with the output devices.
The fstream library

▪ The fstream library allows us to work with files.


▪ To use the fstream library, include both the standard
<iostream> AND the <fstream> header file:
▪ There are three classes included in the fstream library,
which are used to create, write or read files:
Create and Write To a File

▪ To create a file, use either the ofstream or fstream class, and


specify the name of the file.
▪ To write to the file, use the insertion operator (<<).

You must always


close a file as it
is considered
good practice,
and it can clean
up unnecessary
memory space.
Read from a File

▪ To read from a file, use either the ifstream or fstream


class, and the name of the file.
▪ Note that we also use a while loop together with the
getline() function (which belongs to the ifstream class)
to read the file line by line, and to print the content of
the file.
Example
Using fstream to read and write to
files

▪ To use fstream for reading and writing purposes you


must create an fstream object as follows:
▪ To open a file use the object along with the open()
method , open takes two parameters the name of a file
as a string and an opening mode parameter which
determines how to open a file.

Opening Mode explained

▪ The file read operation specified by the mode parameter ios::in


requires that a file must exist prior to reading; ios::out, on the
other hand, creates the file if not found. A file can be opened in
read write mode at the same time when using the fstream
object.
▪ The parameter ios::binary implies that we are opening a file in
binary mode. Reading and writing data items with extraction(<<)
and insertion(>>) operators or by using the getline function is
inefficient if a file is opened in binary mode. In such a case, the
right way is to use write and read functions of ostream
(ofstream) and istream (ifstream) objects.
▪ read(buffer, size);
▪ write(buffer, size);
Example: Using fstream for file
handling.

Is_open():
returns true if
the file has been
opened
successfully and
false if it has
failed.
Example : file handling using
ifstream and ofstream
Activties

▪ Create a program that accepts the names of students as


an input and stores them in a file.
▪ Read from the file and display it to your user.
Types of Files

▪ There are two major groups of files in C++.


– Sequential access files.
– Random access files.
Sequential Files in C++

▪ A Sequential file has to be Accessed in the same order the file was
written.
▪ Let's take an example of Cassette Tapes: We play music in the same
order it was recorded. we can Quickly fast-forward or rewind over
songs we don't want to listen to, but the order of the songs dictates
what we do to play the song we want. But it is difficult, and
sometimes impossible, to insert data in the middle of two other
songs on a tape. The Only way to truly add or delete records from
the middle of a Sequential file is to create a completely New file
that combines both old and new records.
▪ A file created with the help of C++ standard library functions does
not impose any structure on how the data is to be persisted.
However, we are able to impose structure programmatically
according to the application requirement.
Opening Sequential files

▪ A File must be opened before we can read from it or write to it. We


can use the fstream object to open a file for writing or reading
purpose. but if we use ofstream object, we can open a file for
writing purpose only. Following is the Standard Syntax to Open File.

▪ Where Myfile is an object of type fstream, because fstream is a


class we need to create an object to use member function of
fstream class. Next, using myFile object we call a member function
open() , this Function Need two arguments to processing. The first
is FileName and the second is File Opening Mode. A File can be
opened in Different modes to perform reading and Writing
Operations. C++ supports the following file open modes:
Opening Mode Detailed explanation

The default value for


fstream mode parameter
is in | out which means
that the file is opened for
reading and writing
when we use the fstream
class.

When using the ofstream


class, however, the
default for mode
parameter is out and for
the ifstream class it is in.

We can use More than


one file mode using the
bit wise operator " | "
Closing a File

▪ A File must be closed after the completion of all


operations related to the file. When the C++ program
terminates, it automatically flushes all the streams,
releases all the allocated memory, and closes all the
opened files. But it is always a good practice that a
programmer should close all the opened files before
program termination. Following is the standard syntax for
closing a file:

▪ Close() is a member function of fstream, ifstream and


ofstream objects.
Writing To and Reading from
sequential files

▪ While creating C++


programs, we write
information to a file from
our program using
streams insertion
Operator << just as we
use that operator to
output information to the
screen. The only
difference is that we use
an ofstream or fstream
object instead of the cout
object.
Example
Random Access Files

▪ So far, all of the file access we’ve done has been sequential --
that is, we’ve read or written the file contents in order. However,
it is also possible to do random file access -- that is, skip around
to various points in the file to read its contents. This can be
useful when your file is full of records, and you wish to retrieve a
specific record. Rather than reading all of the records until you
get to the one you want, you can skip directly to the record you
wish to retrieve.
▪ Once you have a file open for processing, you can navigate to
different parts of the file. This is often referred to as random
access of files. It really means that you aren't at the beginning or
the end. Two functions are available:
– istream: seekg() (or seek and get)
– ostream: seekp() (seek and put)
Random file access

▪ Random file access is done by manipulating the file


pointer using either seekg() function (for input) and
seekp() function (for output). In case you are wondering,
the g stands for “get” and the p for “put”. For some
types of streams, seekg() (changing the read position)
and seekp() (changing the write position) operate
independently -- however, with file streams, the read
and write position are always identical, so seekg and
seekp can be used interchangeably.
Random file access

▪ The seekg() and seekp() functions take two parameters. The


first parameter is an offset that determines how many bytes
to move the file pointer. The second parameter is an ios flag
that specifies what the offset parameter should be offset
from.

▪ A positive offset means move the file pointer towards the


end of the file, whereas a negative offset means move the
file pointer towards the beginning of the file.
▪ Infile is an ifstream object.
Seekg()

▪ Stands for seek and get


▪ Used to adjust the position of the file pointer for reading
purposes
▪ Example
Seekp()

▪ Stands for seek and put


▪ Used to adjust the position of the file pointer for writing
purposes
▪ Example
tellp() and tellg()

▪ return the absolute position of the file pointer. This can


be used to determine the size of a file:
Example
Using Fstream for
input and output
simultaneously
This program finds vowels found in a text file and replaces
them with #
Example
Part one:
Example part two:

You might also like