You are on page 1of 37

DILLA UNIVERSITY

COLLEGE OF ENGINEERING AND TECHNOLOGY


SCHOOL OF COMPUTING AND INFORMATICS
DEPARTMENT OF COMPUTER SCIENCE
Fundamental of Programming –II in C++
Chapter – File Management in C++

Prepared by Nega Teferra (M.Tech on CSE)


1
Introduction
 All programs we looked earlier:
 input data from the keyboard.
 output data to the screen.
 Output would be lost as soon as we exit from the program.
 How do we store data permanently?
 We can use secondary storage device.
 Data is packaged up on the storage device as data structures called files.
 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
Prepared by Nega Teferra (M.Tech on CSE) 2
Streams
A flow of characters
Input stream Output stream
– Flow into program – Flow out of program
Can come from keyboard Can go to screen
Can come from file Can go to file

 The C++ file system is designed to work with a wide variety


of devices, including terminals, disk drives, and tape drives.
 Even though each device is very different, the C++ file
system transforms each into a logical device called stream.

Prepared by Nega Teferra (M.Tech on CSE) 3


Cont.…
There are two types of streams: text and binary.
1. Text Streams
 A text stream is a sequence of characters.
 In a text stream, certain character translations may occur as
required by the host environment.
 For example a new line may be converted to a carriage
return/linefeed pair.
 There may not be a one-to-one relationship between the characters
that are written (or read) and those on the external device.
2. Binary streams
 A binary stream is a sequence of bytes with a one-to-one
correspondence to those in the external device i.e., no character
translations occur.
 The number of bytes written (or read) is the same as the number on
the external device. Prepared by Nega Teferra (M.Tech on CSE) 4
Text Vs Binary File
 Text files are special subset of binary files that are used to store
human readable characters as a rich text document or plain text
document.
 Text files also store data in sequential bytes but bits in text file
represents characters.
 Text files are less prone to get corrupted as any undesired change
may just show up once the file is opened and then can easily be
removed.
 Binary file are those typical files that store data in the form of
sequence of bytes grouped into eight bits or sometimes sixteen bits.
These bits represent custom data and such files can store multiple
types of data (images, audio, text, etc) under a single file.
 Binary file can have custom file formats and the developer, who designs
these custom file formats, converts the information, to be stored, in
bits and arranges these bits in binary file so that they are well
understood by the supporting application and when needed, can easily
be read by the supporting application. Prepared by Nega Teferra (M.Tech on CSE) 5
Cont.… By default, C++ opens the files in text mode.
Text File Binary File
Bits represent character. Bits represent a custom data.
Less prone to get corrupt as Can easily get corrupted, even a
changes reflect as soon as the file single bit change may corrupt the
is opened and can easily be undone. file.
Can store different types of data
Can store only plain text in a file.
(image, audio, text) in a single file.
Widely used file format and can be Developed especially for an
opened using any simple text application and may not be
editor. understood by other applications.
Mostly .txt and .rtf are used as Can have any application defined
extensions to text files. extension.
Prepared by Nega Teferra (M.Tech on CSE) 6
The fstream Library
 To use the fstream library, include both the standard <iostream>
AND the <fstream> header file:
 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.

Prepared by Nega Teferra (M.Tech on CSE) 7


Text File processing
File processing involves the following major steps
1. Declaring file variable identifier
2. Opening the file
3. Processing the file
4. Closing the file when process is completed.

Prepared by Nega Teferra (M.Tech on CSE) 8


How to Open Files
 We need to tell the computer the purpose of opening our
file.
 For e.g.- to write on the file, to read from the file, etc.
 Before performing any operation on a file, you must first
open it. If you need to write to the file, open it using
fstream or ofstream objects.
 If you only need to read from the file, open it using the
ifstream object.
 The three objects, that is, fstream, ofstream, and
ifstream, have the open() function defined in them. The
function takes this syntax:
open (file_name, mode);

Prepared by Nega Teferra (M.Tech on CSE) 9


Cont.…
 These are the different modes in which we can open a file.
 It is possible to use two modes at the same time. You combine
them using the | (OR) operator.
Mode Description
ios::app opens a text file for appending. (appending means
to add text at the end).
ios::ate opens a file for output and move the read/write
control to the end of the file.
ios::in opens a text file for reading.
ios::out opens a text file for writing.
ios::trunc truncates the content before opening a file, if
file exists.
Prepared by Nega Teferra (M.Tech on CSE) 10
Cont.…

 We have opened the file ‘file1.txt' to write on it.


 ‘file1' file must be created in our working directory.
 The default value of (“file1.txt”) mode is (“file1.txt”, ios::out)

Prepared by Nega Teferra (M.Tech on CSE) 11


Closing a file
 C++ automatically close and release all the allocated memory.
 But a programmer should always close all the opened files.
 Following is the standard syntax for close function, which is a
member of fstream, ifstream, and ofstream objects.
void close();

Prepared by Nega Teferra (M.Tech on CSE) 12


Create and Write To a File
 While doing C++ programming, you write information to a file
from your program using the stream insertion operator << just
as you use that operator to output information to the screen.
 The only difference is that you use an ofstream or fstream
object instead of the cout object.

Prepared by Nega Teferra (M.Tech on CSE) 13


Reading from a File:
 You read information from a file into your program using the
stream extraction operator >> just as you use that operator to
input information from the keyboard.
 The only difference is that you use an ifstream or fstream
object instead of the cin object.

Prepared by Nega Teferra (M.Tech on CSE) 14


Functions that can be used to perform special tasks
Operation function Description
Checking end of file. eof() Used to check eof during the reading of file

Check if an operation bad() Returns true if a reading or writing operation fails.


fails.
Check if an operation Fail() Returns true in the same cases as bad(), but also in
fails. the case that a format error happens.
Checking for opened is_open(); Checks if the file is opened or not, returns true if
file. the file is opened else false
Number of bytes already gcount() Returns count of the bytes read from the file
read.
Ignoring characters ignore() Ignores n bytes from the file. (get pointer is
during file read. positioned after n- character)
Checking next peek() Checks the next available character, will not increase
character. the get pointer to next character.
Random access (only for seekg(), seekp() In case of binary files random access is performed
binary files). tellg(), tellp() using these functions. They either give or set the
position of get and put pointers on the particular
location
15
Prepared by Nega Teferra (M.Tech on CSE)
Examples:- Writing text to a file in multiple line

Prepared by Nega Teferra (M.Tech on CSE) 16


Examples:- Reading text from the file which is written in the
previous slide.

Prepared by Nega Teferra (M.Tech on CSE) 17


Example:- Writing text to a file from the keyboard.

Prepared by Nega Teferra (M.Tech on CSE) 18


Example:- Reading text from the file which is written in the
previous slide from the keyboard.

Prepared by Nega Teferra (M.Tech on CSE) 19


File modes
 What if we wanted to append some more data to the end of the file?
 It turns out that the file stream constructors take an optional second parameter that
allows you to specify information about how the file should be opened.
 This parameter is called mode, and the valid flags that it accepts live in the Ios class.
 The following program is appending the file on existing file.

Prepared by Nega Teferra (M.Tech on CSE) 20


File Position Pointers
get and put stream pointers
 All I/O streams objects have, at least, one internal stream
pointer:
 ifstream, like istream, has a pointer known as the get
pointer that points to the element to be read in the next
input operation.
 ofstream, like ostream, has a pointer known as the put
pointer that points to the location where the next element
has to be written.
 Finally, fstream, inherits both, the get and the put
pointers, from iostream (which is itself derived from both
istream and ostream).

Prepared by Nega Teferra (M.Tech on CSE) 21


C++ put() function
The put() function is member of ofstream class.
It is used to write single character into file.

Prepared by Nega Teferra (M.Tech on CSE) 22


Functions to work with the put pointer
 When we open the file in a write-only mode i.e. "ios::out", the
put pointer is automatically set the beginning of the file, to
allow us to read the file from its start.
 But we are also provided some functions which allow us to -
 Access the current location of the put pointer.
 Allow us to set the put pointer at the particular location in a file.
Functions to use put pointer Description
Gives us the current location of the put pointer. When the
file is opened in a write-only mode, tellg() returns zero i.e.
tellp()
the beginning of the file.

This function is used to set the location of the put pointer to


a desired position/offset.
seekp (streampos position ); The position variable is the new position in the file i.e. an
integer value representing the number of bytes from the
beginning of the file.
Prepared by Nega Teferra (M.Tech on CSE) 23
Cont.…
 This function is used to set the location of
the put pointer to a desired position/offset.
 The position parameter is the new position in the file
i.e. an integer value representing the number of bytes
seekp ( streamoff from the beginning of the file.
offset,  The position parameter is relative to the dir parameter.
ios_base::seekdir dir is the seeking direction and it can take any of the
dir ); constant values:

ios::beg - offset from the beginning of the file.


ios::cur - offset from the current position in the file.
ios::end - offset from the end of the file.

Prepared by Nega Teferra (M.Tech on CSE) 24


Example

Prepared by Nega Teferra (M.Tech on CSE) 25


Cont.…
ofstream_ob.seekp(-1, ios::cur);
 This line of code calls the seekp()function which takes the put
pointer(used to write the content of a file) to one byte position
back from the current position of put pointer, after the searched
character e is found.
 This was important because after calling the get() function to get a
character, both the get and put pointer move to the next byte
position.
 This has been made possible by -
 By setting the first parameter of seekp() function i.e. offset
position to -1.
 And by setting the second parameter seekp() function i.e. flag
to "ios::cur".
Prepared by Nega Teferra (M.Tech on CSE) 26
C++ get() Function
The get() function is member of ifstream class
get() function, used to read a character from the file.

Prepared by Nega Teferra (M.Tech on CSE) 27


Functions to work with the get pointer
 When we open the file in a read-only mode i.e. "ios::in", the
get pointer is automatically set the beginning of the file,
to allow us to read the file from its start.
 But we are also provided some functions which allow us to -
 Access the current location of the get pointer.
 Allow us to set the get pointer at the particular location in a file.
Functions to use get pointer Description
Gives us the current location of the get pointer.
tellg() When the file is opened in a read-only mode, tellg() returns
zero i.e. the beginning of the file.
This function is used to set the location of the get pointer
to a desired position/offset. The position variable is the new
seekg (streampos position );
position in the file i.e. an integer value representing the
number of bytes from the beginning of the file.
Prepared by Nega Teferra (M.Tech on CSE) 28
Cont.…
 This function is used to set the location of
the get pointer to a desired position/offset.
 The position variable is the new position in the file i.e. an
integer value representing the number of bytes from the
seekg ( streamoff beginning of the file.
offset,  The position variable is relative to the dir parameter. dir
ios_base::seekdir is the seeking direction and it can take any of the
dir ); following constant values:

ios::beg - offset from the beginning of the file.


ios::cur - offset from the current position in the file.
ios::end - offset from the end of the file.

Prepared by Nega Teferra (M.Tech on CSE) 29


Example

Prepared by Nega Teferra (M.Tech on CSE) 30


Cont.…
ifstream_ob.seekg(0, ios::beg);
 This line of code calls the seekg()function which takes the get pointer(used to
read the content of a file) to the beginning of the file after we have already
read the file once, only to read it for the second time.
 This has been made possible by -
 By setting the first parameter of seekg() function i.e. offset position to 0.
 And by setting the second parameter seekg() function i.e. flag to "ios::beg".

ofstream_ob.clear();
 Once the reading of content of a file completes, the EOF(End of file) is reached
and the EOF flag is set on which does not allow us to access of file again for
reading it again.
 Hence, a call to clear() function is very critically important because it sets the
EOF flag off, which allows us to re-read the content of file.
Prepared by Nega Teferra (M.Tech on CSE) 31
Binary File processing
 For binary files, reading and writing data with the extraction and
insertion operators (<< and >>) and functions like getline is not
efficient, since we do not need to format any data and data is likely
not formatted in lines.
 File streams include two member functions specifically designed to
read and write binary data sequentially: write and read.
 The first one (write) is a member function of ostream (inherited by
ofstream).
 And read is a member function of istream (inherited by ifstream).
 Objects of class fstream have both. Their prototypes are:
write ( memory_block, size );
read ( memory_block, size );
 Where memory_block is of type char* (pointer to char), and
represents the address of an array of bytes where the read data
elements are stored or from where the data elements to be written
are taken.
 The size parameter is an integer value that specifies the number of
characters to be read or written from/to the memory block.
Prepared by Nega Teferra (M.Tech on CSE) 32
Example:- Read & Write Binary file

Prepared by Nega Teferra (M.Tech on CSE) 33


C++ write() function
 The write() function is used to write object or record
(sequence of bytes) to the file.
 A record may be an array, structure or class.
 The write() function takes two arguments.
&obj : Initial byte of an object stored in memory.
sizeof(obj) : size of object represents the total number
of bytes to be written from initial byte.
ofstream_obj.write( (char *) &obj, sizeof(obj) );

Prepared by Nega Teferra (M.Tech on CSE) 34


Example:

Prepared by Nega Teferra (M.Tech on CSE) 35


C++ read() function
 The read() function is used to read object (sequence of
bytes) to the file.
 The read() function takes two arguments.
 &obj : Initial byte of an object stored in file.
 sizeof(obj) : size of object represents the total number of
bytes to be read from initial byte.
ifstream_obj.read( (char *) &obj, sizeof(obj) );

 The read() function returns NULL if no data read.

Prepared by Nega Teferra (M.Tech on CSE) 36


Example:

37
Prepared by Nega Teferra (M.Tech on CSE)

You might also like