0% found this document useful (0 votes)
2 views8 pages

Chapter 4 - Files

Chapter Four discusses file handling in C++, emphasizing the importance of managing files for data storage and retrieval. It explains the concepts of streams, file types (text and binary), and the use of C++ file I/O classes such as ifstream, ofstream, and fstream for reading and writing files. The chapter also outlines the steps for processing files, including opening, reading, writing, and closing files, along with examples of basic file operations.

Uploaded by

negedetekleyes33
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)
2 views8 pages

Chapter 4 - Files

Chapter Four discusses file handling in C++, emphasizing the importance of managing files for data storage and retrieval. It explains the concepts of streams, file types (text and binary), and the use of C++ file I/O classes such as ifstream, ofstream, and fstream for reading and writing files. The chapter also outlines the steps for processing files, including opening, reading, writing, and closing files, along with examples of basic file operations.

Uploaded by

negedetekleyes33
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

Chapter Four: Structure and File Handling in C++

4.1. File Management


File handling is an important part of all programs. Most of the applications will have their
own features to save some data to the local disk and read data from the disk again. Files
which are on the secondary storage device are called physical files. In order to process
file through program, logical file must be created on the RAM. This logical file is nothing
but an object having file data type. As an object there should be a variable identifier that
points to it. This variable is called file variable and some times also called file handler.
C++ File I/O classes simplify such file read/write operations for the programmer by
providing easier to use classes.

4.2. Streams and Files


The I/O system supplies a consistent interface to the C++ programmer independent of the
actual device being accessed. This provides a level of abstraction between the
programmer and the device. This abstraction is called stream. The actual device is called
a file.

4.2.1. Streams
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. There are two types
of streams: text and binary.
a. 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.
Because of possible transformations, the number of characters written (or read) may not
be the same as those on the external device.
b. 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

-1-
read) is the same as the number on the external device. However, an implementation-
defined number of null bytes may be appended to a binary stream. These null bytes might
be used to pad the information so that it fills a sector on a disk, for example.

4.2.2. Files
In C++, a file can be anything from a disk file to a terminal or printer. You associate a
stream with a specific file by performing an open operation. Once a file is open,
information can be exchanged between it and a program. All streams are the same but all
files are not. If the file can support position requests, opening that file also initializes the
file position indicator to the start of the file. As each character is read from or written to
the file, the position indicator is incremented. You disassociate a file from a specific
stream with a close operation. If you close a file opened for output, then contents, if any,
of its associated stream are written to the external device. -- this process is referred to as
flushing the stream. All files are closed automatically when the program terminates
normally. Files are not closed when a program terminates abnormally. Each stream that is
associated with a file has a file control structure of type FILE. This structure FILE is
defined in the header stdio.h.

[Link]. The standard streams


When ever a program starts execution, three streams are opened automatically.
stdin --- standard input.
stdout -- standard output
stderr -- standard error
Normally, these streams refer to the console. Because the standard streams are file
pointers, they can be used by the ANSI C file system to perform I/O operations on the
console.

[Link]. C++ File I/O Classes and Functions


To perform file I/O, the header file fstream.h is requied. fstream.h defines several classes,
including ifstream, ofstream, and fstream. These classes are derived form istream and
ostream, repectively. istream and ostream are derived form ios.
Three file I/O classes are used for File Read/Write operations:
a. ifstream - Can be used for File read/input operations

-2-
b. ofstream - Can be used for File write/output operations
c. fstream - Can be used for both read/write c++ file I/O operations
These classes are derived directly or indirectly from the classes istream, and ostream. We
have already used objects whose types were these classes: cin is an object of class istream
and cout is an object of class ostream. Therefore, we have already been using classes that
are related to our file streams. And in fact, we can use our file streams the same way we
are already used to use cin and cout, with the only difference that we have to associate
these streams with physical files. Let's see an example:

4.2.3. Text and Binary Files


In file processing, files are generally classified into two as
 Text file and
 Binary file
Text file is a file in which its content is treated as a sequence of characters and can be
accessed sequentially. Where as binary file is a file in which its content is treated as
record sequence in a binary format. Binary format refers to the actual format the data is
going to be placed and processed in the memory which is directly related to its data type.
For example, the value int count 321 will be stored in three byte if it is written in text file
considering the digit sequence ‘3’, ‘2’, ‘1’. It will be stored in two byte if it is written in
binary file since int requires two byte to store any of its value. When you open the binary
file you will see the character equivalence of the two bytes.
321 in binary equals 0000 0001 0100 0001
The first byte holds the character with ASCII value equals to one and the second byte a
character with ASCII value equals 65 which is ‘A’. Then if you open the binary file you
will see these characters in place of 321.

4.2.4. 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.

-3-
[Link]. Opening and Closing a file
An open file is represented within a program by a stream object and any input or output
operation performed on this stream object will be applied to the physical file associated to
it. In C++, you open a file by linking it to a stream. Before you can open a file, you must
first obtain a stream. There are three types of streams: input, output, and input/output. To
create an input stream, you must declare the stream to be of class ifstream. To create an
output stream, you must declare it as class ofstream. Streams that will be performing
both input and output operations must be declared as class fstream.
ifstream in ; //input stream
ofstream out ; // output stream
fstream io ; // input and output
Once you have declared a stream, you associate it with a file by using the method open().
The method open ( ) is a member of each of the three stream classes. Its prototype is:
void open (const char *filename, int mode, int access = filebuf::penprot );
Where:
Filename is the name of the file.
The value of the mode determines how the file is opened. It must be one (or more) of
these values:
Mode Description

ios::app Write all output to the end of the file

ios::ate Open a file for output and move to the end of the file (normally used to append
data to a file). Data can be written anywhere in the file.

ios::binary Cause the file to be opened in binary mode.


ios::in Open a file for input
ios::nocreate If the file does not exist, the open operation fails.

ios::noreplace If the file exists, the open operation fails.


ios::out Open a file for output
ios:trunc Discard the file's content if it exists (this is also the default action ios::out)

You can combine two or more of these values by using them together.
ofstream out ;
[Link] ( "test", ios::out); // correct statement
ofstream out1 ;
[Link] ( " test"); // the default value of mode is ios::out –
// correct statment

-4-
To open a stream for input and output, you must specify both the ios::in and the ios::out
mode values. (Noe default value for mode is supplied in this case.)
fstream myStream;
[Link] ( "test", ios::in | ios::out );
If open ( ) fails, myStrream will be zero
if (myStream){
cout << "Cannot open a file.\n";
// handle error
}
Each one of the open() member functions of the classes ofstream, ifstream and fstream
has a default mode that is used if the file is opened without a second argument:
class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed, even if a mode that does not include them is passed as second argument to the
open() member function. The default value is only applied if the function is called
without specifying any value for the mode parameter. If the function is called with any
value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of
any format considerations. Non-binary files are known as text files, and some translations
may occur due to formatting of some special characters (like newline and carriage return
characters).
Since the first task that is performed on a file stream object is generally to open a file,
these three classes include a constructor that automatically calls the open() member
function and has the exact same parameters as this member. Therefore, we could also
have declared the previous myfile object and conducted the same opening operation in
our previous example by writing:
ofstream myfile ("[Link]", ios::out | ios::app | ios::binary);
Combining object construction and stream opening in a single statement. Both forms to
open a file are valid and equivalent.

-5-
To check if a file stream was successful opening a file, you can do it by calling to
member is_open() with no arguments. This member function returns a bool value of true
in the case that indeed the stream object is associated with an open file, or false
otherwise:
if (myfile.is_open()) { /* ok, proceed with output */ }
ifstream myStream ( "myfile" ); // open file for input
When we are finished with our input and output operations on a file we shall close it so
that its resources become available again. In order to do that we have to call the stream's
member function close(). This member function takes no parameters, and what it does is
to flush the associated buffers and close the file:
[Link]();
Once this member function is called, the stream object can be used to open another file,
and the file is available again to be opened by other processes.
In case that an object is destructed while still associated with an open file, the destructor
automatically calls the member function close(). The close method takes no parameters
and returns no value.

[Link]. Reading and writing text files


Simply use the << and >> operators in the same way you do when performing console
I/O except that instead of using cin and cout, you substitute a stream that is linked to a
file.
ofstream out ("inventory");
out <<"Radios" << 39.95 << endl;
out << "Toastors" << 19.95 << endl;
[Link] ( );
Example: Basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
[Link] ("[Link]");
myfile << "Writing this to a file.\n";
[Link]();
return 0;

-6-
}
This code creates a file called [Link] and inserts a sentence into it in the same way
we are used to do with cout, but using the file stream myfile instead.
Example 2: writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("[Link]");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
[Link]();
}
else cout << "Unable to open file";
return 0;
}
Example 3: reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("[Link]");
if (myfile.is_open())
{
while (! [Link]() )
{
getline (myfile,line);
cout << line << endl;
}
[Link]();
}

else cout << "Unable to open file";

return 0;
}
This last example reads a text file and prints out its content on the screen. Notice how we
have used a new member function, called eof() that returns true in the case that the end of
the file has been reached. We have created a while loop that finishes when indeed
[Link]() becomes true (i.e., the end of the file has been reached).

-7-
Exercise
1. Write a program that accept student information from the keyboard & store it on a file
“D:/[Link]” in a text file format
2. Write a program that reads students information from the text file “D:/ [Link]” and
display on the screen.
Note Student record consists of first name, last name, gender, age and Id.

-8-

You might also like