|
|
Summary
1) Files
2) Text File Handling
3) Example 1
4) Output File Handling
5) Example 2
6) Tips
Files
We will discuss files and file
handling in this lecture. The
topic is going to be a sequel of
the subjects like
bit, bytes, character, numbers etc.
In the previous lecturers, we
have
talked about strings, which are actually character arrays.
These all the subjects when
combined together, becomes a program.
While typing a letter
or a document in word
processor, we actually deal with big collection of words like sentences, not with
bits and
bytes. These combinations of characters, words,
sentences and paragraph are
called as
files. The files in the computer are classified under different categories. Primarily,
there
are two types of files
i.e. text files and executable
program files. Text files consist of
readable English characters.
These include our simple text files, or word processor file
etc. On the other hand,
the executable program files run the program. In the dos
(command prompt window), when we
write the command ‘dir’,
a list of files is
displayed. Similarly,
Windows explorer is used in the
windows. Click on some
folder to
see the list of the files in that folder in the right panel. These are the names
of the files,
which we see. The file properties show the length of the file, date of creation
etc. One
category of data files is plain text files. We can create plain text files using
the windows
notepad, type the text and save it. It is
an ordinary text,
which means that
there is no
formatting of text involved.
We can view this text using the ‘type’ command of the dos
(type filename). Similarly, our source programs are also plain text files. There
is no
formatted text in cpp files. There
is another kind of text
files, which are not plain
ones.
Deleted: Handout
Deleted: Lecture No. 18¶
Deleted: Chapter. 14
Deleted: Example 1
Deleted: Example 2
Deleted: Today’s topic is about
Deleted: handling. We have been
talking about
Deleted: Then we discuss
Deleted: When we combine all these
things, it
Deleted: We type
Deleted: processor. Similarly, we can
have essays, novels as a
Deleted: bigger collection of words,
sentences. These are no longer bits and
bytes. We call these
Deleted: sentences, paragraph as files.
There are many types of files in the
computer. Primarily
Deleted: The other type is executable
programs, which runs on
Deleted: issue
Deleted: windows, click
Deleted: Files can contain data or there
are program files.
Deleted: note pad,
Deleted: meaning
Deleted: involves and we
Deleted: Today we will be discussing
plain text files
Deleted: are
Deleted: text files.
Page 208
These are the word processor
files, containing text that
is formatted like, bold, italic,
underline, colored text and tables. This formatting information is also stored in
the file
along with the text.
Therefore such files are not plain text files. Same thing applies
to
spreadsheets having formatting,
formulae, cell characteristic
etc. Though these
files
contain some binary information along with the text,
yet these are not program
files. We
created these files using some other program like Microsoft Word, excel etc. Such
files
also fall in the
category of text files. The other type is the program file that executes on
the computer. Normally,
executable files contain only
non-printable binary information.
There are different ways of handling these files.
Today we will see what is the utility of files in our programs. We know that
all the
information in the computer memory is volatile. It means when we turn off the computer
that information will be lost. The data, written in
a program, is actually the
part of the
program and is saved on the disk. Whenever we execute the program that data
will be
available. Suppose
we have to develop a payroll system for a factory.
For this purpose,
we will at first
need to gather the data like name of
the employees, their salaries
etc.
Enter all this information before getting their attendance. After collecting all
the
information, you can calculate their salary and print a report of the salary. Now
the
question arises whether we will have to enter the name and salary of employees
every
month. The better way is to store this information once and re-use
it every month. We can
save this information in a file and
can calculate the salary after
getting the current
month’s attendance of
employees. We have to
do all the calculations
again in case of not
saving the report on the disk. It will be nicer if we have saved the output
file on the disk.
We can take the print out whenever we need. We are discussing this just to
give you the
justification of using files. The data in the memory is volatile.
Similarly, the data, which
we key in the program during the execution of a program, is also volatile. To save
the
data on permanent
basis, we need
files so that we keep these on the disk and can use
whenever needed. Now
there is need to learn how to create a file on the disk, read from
the file, and
write into the file and how to manipulate the data in
it. This is the file
handling.
Text file Handling
Let's see what are the basic steps
needed for file handling.
Suppose we have a file on the
disk and want to open it. Then read from or write into the file
before finally closing it.
The basic steps of file handling are:
• Open the file
• Read and write
• Close the file
We have been using cin
and cout
a lot in the programs.
We know that these are the doors
by which data can enter and come out.
cin is used to enter the
data and cout is
used to
display the data on the screen. Technically,
these are known as streams
in C++. We will
discuss in detail about streams in later lectures. Today we will see some more streams
about file handling. This is how
'C++
language' handles files. For this purpose, the
header file to be used is <fstream.h>
(i.e. file stream). Whenever using files in
the
program, we will include this header file as
#include <fstream.h>. These
streams are
Deleted: files. These files contain text
but this text
Deleted: text, therefore
Deleted: on spreadsheets, which
contain
Deleted: formulas,
Deleted: but
Deleted: lie
Deleted: s
Deleted: binary information, which is
not printable.
Deleted: ¶
So far, we have been using characters,
numbers in our program. Then we learn
how to use arrays and strings, which are
actually character arrays. Today we will
learn how to use files in the program. The
question arises why we want to use
Deleted: which is
Deleted: the program is
Deleted: is
Deleted: Now suppose
Deleted: First
Deleted: employees, their salary etc.
Enter all this information, then get their
attendance, and then calculate their
salary. Finally print a report of their
salary. Are we going
Deleted: month?
Deleted: then by
Deleted: employees can calculate the
salary. Similarly, do we need to save the
Deleted: again, if we did not save
Deleted: disk, we
Deleted: feel for the
Deleted: files
Deleted: we needed. So we have
Deleted: the file.
Deleted: Today we will discuss text file
Deleted: Lets look
Deleted: we need
Deleted: disk. First we need to open
Deleted: and then finally close the file.
Deleted: our
Deleted: C++
Deleted: and not
C
Deleted: we are
Deleted: our
... [3]
... [1]
... [2]
Page 209
used the way we have
been employing
cin
and
cout but
we can do more with these
streams. While handling
files, one can have three options.
Firstly, we will only
read the
file i.e. read only file. It means the file is used as input for the program. We
need to have
a stream for input file
i.e.
ifstream (input file stream).
Similarly, if we want
to write in
some file, ofstream
(output file stream)
can be used. Sometimes
we may need to read and
write in the same file. One way is to read from a file, manipulate it and write
it in another
file, delete the original file and renaming the new file with the deleted file name.
We can
read, write and manipulate the same file using
fstream.h.
Let's us see how can we use these
files in our programs.
First, we have to include the
fstream.h in our programs. Then we need to declare file streams.
cin and
cout are
predefined
streams which needed not to be declared. We can declare file stream as:
ifstream inFile; // object for reading from a file
ofstream outFile; // object for writing to a file
The variables inFile
and outFile
are used as 'handle
to refer' files. These are like internal
variables, used to handle the files that are on the
disk. We will use
inFile as declared
above to read a file. Any meaningful and self-explanatory name can be used.
To deal
with a payroll system,
payrollDataFile
can be used as a file stream variable i.e.
ifstream
payrollDataFile;.
Consider the following statement:
ifstream myFile;
Here myFile is an
internal variable used
to handle the file. So far, we did not attach a file
with this handle. Before
going for attachment, we will have to open a file. Logically,
there is function named ‘open’ to open a file.
While associating a file
with the variable
myFile, the syntax
will be as under:
myFile.open(filename);
You have noted that this is a new way of function calling. We are using dot (.)
between
the myFile and
open function.
myFile is an object
of ifstream
while
open() is a function
of ifstream. The
argument for the open
function filename
is the name of the file on the
disk. The data type of argument
filename is character string,
used to give the
file name in
double quotation marks. The file name can be simple file name like “payroll.txt”.
It can
be fully qualified path name like “C:\myprogs\payroll.txt”. In
the modern operating
systems like Windows, disks are denoted as C: or D:
etc. We have different
folders in it
like ‘myprogs’ and can have files in this folder. The fully qualified path means
that we
have to give the path
beginning from C:\.
To under stand it further, suppose that we are working in the folder ‘myprogs’
and our
source and executable files are also in this folder.
Here, we don’t need to
give a complete
path and can write it
as “payroll.txt”.
If the file to be opened is in the current directory
(i.e. the program and text file are in the same
folder), you can open
it by simply giving
the name. If you are not familiar with the windows file system, get some
information
from windows help system. It is a
hierarchical system. The disk,
which is at the top,
Deleted: in similar way we have been
using cin and
Deleted: cout,
but we can do more with
these streams. Now we
Deleted: First option is
Deleted: and that stream is
Deleted: need
Deleted: we will use
Deleted: Let us take a look
Deleted: predefined streams therefore
we did not declare these.
Deleted: handle to refer
Deleted: variables which will be
Deleted: disk. If we want to read a file,
we
Deleted: above. We can use any name
here, which is meaningful and selfexplanatory.
Suppose if
Deleted: system, we can declare a
Deleted: as:
Deleted: variable, which will be used o
Deleted: First, we need to open a file
and logically
Deleted: How can we use the open
function? As we want to associate
Deleted: myFile.
The syntax is as;
Deleted: and
Deleted: , this
Deleted: can
Deleted: or it
Deleted: etc and we
Deleted: starting from C:\. There is
another short hand for this. If
Deleted: In this case,
Deleted: the
Deleted: folder) then we
Deleted: its
Deleted: hierarchal system. At the top
is disk, which
Page 210
contains folder and files. Folders can contain subfolders and files.
It is a multi-level
hierarchical system. In UNIX, the top level is “root”, which contains files
and directories.
So it’s like a bottom-up
tree. Root is at the top
while the branches are
spreading
downward. Here ‘root’ is considered as root of a tree and files or subfolders are
branches.
To open a file,
we use open
function while
giving it the name of the file as fully qualified
path name or simple name. Then we also tell it what we want to do with that file
i.e. we
want to read that file or write into that file or want to modify that file. We have
declared
myFile as ifstream
(input file stream) variable so whenever we tried to open a file with
ifstream variable it can only be opened for input. Once the file is open,
we can read it.
The access mechanism is same,
as we have been using with streams. So to read a word
from the file we can write as:
myFile >> c;
So the first word of the file will be read in c, where c is a character array. It
is similar as
we used with cin.
There are certain limitations to this. It can read just one word at one
time. It means, on encountering a space, it will stop reading further. Therefore,
we have
to use it repeatedly to read the complete file. We can also read multiple words
at a time
as:
myFile >> c1 >> c2 >> c3;
The first word will be read in c1, 2nd in c2 and 3rd
in c3. Before reading the file, we
should know some information regarding the structure of the file. If we have a file
of an
employee, we should know that the first word is employee’s
name, 2nd word is salary etc,
so that we can read the first word in a
string and 2nd
word in an int
variable. Once we
have read the file, it must be closed. It is the responsibility of the programmer
to close the
file. We can close the file as:
myFile.close();
The function close()
does not require any argument, as we are going to close the file
associated with myFile.
Once we close the file, no file is associated with
myfile now.
Let’s have a look on error checking mechanism while handling files. Error
checking is
very important. Suppose we have to open a text file
myfile.txt from the current
directory,
we will write as:
ifstream myFile;
myFile.open(“myfile.txt”);
If this file does not exist on the disk, the variable
myFile will not be associated
with any
file. There may be many reasons due to which the
myFile will not be able
to get the
handle of the file. Therefore, before going ahead,
we have to make sure that the file
opening process
is successful. We can write as:
Deleted: It’s a multilevel hierarchal
Deleted: bottom up tree, root
Deleted: and
Deleted: and give
Deleted: time, it mean whenever it
encounters a space
Deleted: Lets take
Page 211
if (!myFile)
{
cout << “There is some error opening file” << endl;
cout << “ File cannot be opened” << end;
exit(1);
}
else
cout << “ File opened successfully “ << end;
Example 1
Let’s write a
simple program,
which will read from a file
‘myfile.txt’ and print
it on the
screen. “myfile.txt”
contains employee’s
name, salary and department of employees.
Following is the complete program
along with “myfile.txt”
file.
Sample “myfile.txt”.
Name Salary Department
Aamir 12000 Sales
Amara 15000 HR
Adnan 13000 IT
Afzal 11500 Marketing
Code of the program.
/*
* This program reads from a txt file “myfile.txt” which contains the
* employee information
*/
#include <iostream.h>
#include <fstream.h>
main()
{
char name[50]; // used to read name of employee from file
char sal[10]; // used to read salary of employee from file
char dept[30]; // used to read dept of employee from file
ifstream inFile; // Handle for the input file
char inputFileName[] = "myfile.txt"; // file name, this file is in the current directory
inFile.open(inputFileName); // Opening the file
// checking that file is successfully opened or not
Deleted: Below are
Deleted: and a sample
Deleted: Name Salary Department¶
Aamir 12000 Sales¶
Amara 15000 HR¶
Adnan 13000 IT¶
Afzal 11500 Marketing
Deleted: /* ¶
* This program reads from a txt file
“myfile.txt” which contains the ¶
* employee information ¶
*/¶
¶
#include <iostream.h>¶
#include <fstream.h>¶
¶
main()¶
{¶
ifstream inFile; //
Handle for the input file¶
char inputFilename[] = "myfile.txt";
// file name, this file is in the current
directory¶
inFile.open(inputFilename);
// OPening the file¶
¶
// checking that file is successfuly
opened or not¶
if (!inFile) ¶
{¶
cout << "Can't open input file named "
<< inputFilename << endl; exit(1); ¶
} ¶
¶
char name[50]; // used to read name
of employee from file¶
char sal[10]; // used to read salary
of employee from file¶
char dept[30]; // used to read dept of
employee from file ¶
// Reading the complete file word by
word and printing on screen¶
while (!inFile.eof()) ¶
{ ¶
inFile >> name >> sal >> dept;¶
cout << name << "\t" << sal << " \t"
<< dept << endl; ¶
}¶
inFile.close();¶
}
... [4]
... [5]
Page 212
if (!inFile)
{
cout << "Can't open input file named " << inputFileName << endl;
exit(1);
}
// Reading the complete file word by word and printing on screen
while (!inFile.eof())
{
inFile >> name >> sal >> dept;
cout << name << "\t" << sal << " \t" << dept << endl;
}
inFile.close();
}
Output of the program.
Name Salary Department
Aamir 12000 Sales
Amara 15000 HR
Adnan 13000 IT
Afzal 11500 Marketing
In the above program, we have declared three variables for reading the data from
the
input file (i.e. name, sal, dept). The text file “myfile.txt” and the program file
should be in
the same directory as
there is no fully qualified path used with the file name in the
open()
function. After opening the file, we
will check that file
is successfully opened or not. If
there is some error while opening the file,
we will display the error on screen and exit
from the program. The statement
exit(1) is used to exit
from the program at any time and
the control is given back to the operating system.
Later, we will read all
the data from the
file and put it into the variables. The condition in
‘while loop’ is
“!inFile.eof()”
means
until the end of file reached. The function
eof() returns true when
we reached at the end
of file.
Output File Handling
Let’s talk about the output file handling.
You can do several things
with output files like,
creation of a
new file on the disk and
writing data in it. Secondly,
we may like to
open an
existing file and overwrite it
in such
a manner that all the
old information is
lost from it
and new information is
stored. Thirdly, we may want to open an existing file and append
it in the end. Fourthly, an existing file
can be opened and modified in
a way that it can be
written anywhere in the file. Therefore, when we open a file for output we
have several
options and we might
use any one of
these methods. All these
things are related to the
file-opening mode. The actual syntax of open function is:
open (filename, mode)
Deleted: Name Salary Department¶
Aamir 12000 Sales¶
Amara 15000 HR¶
Adnan 13000 IT¶
Afzal 11500 Marketing
Deleted: directory, as we have not
given the
Deleted: are checking
Deleted: Then we are reading
Deleted: ting
Deleted: while loop
Deleted: We
Deleted: files. We may want to create
Deleted: write
Deleted: want
Deleted: will be
Deleted: write new information.
Deleted: we may want to open
Deleted: and want to modify it such
that can write
Deleted: be interested in using
Deleted: the option.
Deleted: file opening
... [6]
Page 213
The first argument is the name of the file
while the second
will be the mode
in which file
is to be opened. Mode is basically an integer variable but its values are pre-defined.
When we open a file for input, its mode is input file that is defined and available
through
the header files,
we have included. So the correct syntax of file opening for input is:
myFile.open(“myfile.txt” , ios::in);
The 2nd argument
ios::in associates
myFile stream object
with the “myfile.txt”
for input.
Similarly, for output files,
there are different modes available. To open a file for output
mode, ios::out is
used. Here is the complete list of modes:
Mode Meaning
in Open a file or stream for extraction (input)
out Open a file or stream
for insertion (output)
app Append rather than
truncate an existing file. Each insertion
(output) will be written to the end of the file
trunc Discards the file’s contents if it exists.
(similar to
default
behavior)
ate Opens the file without
truncating, but allows data to be
written anywhere in the file
binary Treat the file
as binary rather than text. A binary file has
data stored in internal formats, rather than readable text
format
If a file is opened with ios::out
mode, a new file is created.
However, if the file already
exists, its contents will be deleted and
get empty unless you
write something into it. If we
want to append into the
file, the mode will be
ios::app.
When we write
into the file, it
will be added in the end of the file. If we want to write anywhere in the file,
the mode is
ios::ate. We can position at some particular point and can write
there. It is like
append
mode. But in ‘ate
mode’ we can
write anywhere in the file. With the
trunc mode,
the file
is truncated, it is similar to
out mode.
Exercise:
Write a program,
which creates a new file,
and write “Welcome to VU” in it.
The code of the program is:
/*
* This program writes into a txt file “myfileOut.txt” which contains the
* “Welcome to VU”
*/
#include <iostream.h>
#include <fstream.h>
Deleted: and
Deleted: argument is
Deleted: out
Deleted: in
Deleted: trunc
Deleted: ate
Deleted: binary
Deleted: will be
Deleted: file then the mode is
ios::app,
and when
Deleted: there, it
Deleted: mode but in
ate mode
... [11]
... [10]
... [7]
... [9]
... [8]
Page 214
main()
{
ofstream outFile; // Handle for the input file
char outputFileName[] = "myFileOut.txt"; // The file is created in the current directory
char ouputText[100] = "Welcome to VU"; // used to write into the file
outFile.open(outputFileName, ios::out); // Opening the file
// checking that file is successfully opened or not
if (!outFile)
{
cout << "Can't open input file named " << outputFileName << endl;
exit(1);
}
// Writing into the file
outFile << ouputText;
outFile.close();
}
The file “myFileOut.txt”:
Welcome to VU
Exercise:
Write a program, which reads an input file of
employee’s i.e. “employeein.txt”.
Add the
salary of each employee by 2000, and write the result in a new file “employeeout.txt”.
The sample input file “employeein.txt”
Aamir 12000
Amara 15000
Adnan 13000
Afzal 11500
The output file “employeeout.txt” should be as:
Name Salary
Aamir 14000
Amara 17000
Adnan 15000
Afzal 13500
We have been using ‘>>’ sign for reading data from the file.
There are some other
ways
to read from the file. The
get() function is used to get a character from the file, so
that we
can use get() to
read a character and put it in a char variable. The last character in the file
is EOF, defined
in header files. When we are reading file using
get() function the loop
will be as:
Deleted: employees i.e.
“employeein.txt”, add
Deleted: We have
Deleted: ¶
Deleted: it is also
Page 215
char c;
while ( (c = inFile.get()) != EOF)
{
// do all the processing
outFile.put(c);
}
There is one limitation with the ‘>>’
i.e. it does not read
the new line character and in the
output file we
have to insert the new line character explicitly, whereas
get() function
reads each character as it was typed. So if we have to make a copy of a
file, the function
get() should be used. Can we have a function to put a character in the
output file? Yes,
the function to write a single character in the out put file is
put().
So with the output file
stream handle,
we can use this function to write a character in the output file.
Exercise:
Write the above programs using the
get() function and verify
the difference of ‘>>’ and
’get()’ using different input files.
While declaring a variable we initialize it
the way we declare an
integer as int
i.
We
initialize it as i =
0. Similarly
we can declare and initialize an
input or output file stream
variable as:
ifstream inFile(“myFileIn.txt”);
ofstream outFile(“myfileOut.txt”, ios::out);
This is a short hand for initialization. This is same as we open it with
open() function.
Normally we open a file explicitly with the
open() function and close
it explicitly with
close() function. Another advantage of using explicitly opening a file
using the open()
function is, we can use the same variable to associate with other files after closing
the
first file.
We can also read a line from the file. The benefit of reading a line is
efficiency. But
clarity should not be sacrificed over efficiency. We read from the disk and
write to the
disk. The disk is an electro mechanical
device. It is the slowest
component in
the
computer. Other parts like processors, memory etc are very fast nowadays i.e. up
o 2Ghz.
When we talk about hard disk, we say its average access time is 7 mili sec. It means
when
we request hard disk to get data it will take 7 mili sec (7/1000 of a sec) to get
the data
where as processor is running on GHz speed,
a thousand million cycles per sec. Processor
and memory are much much faster than the hard disk. Therefore reading a single
character from the file is too slow.
Nowadays, the buffering
and other techniques are used
to make the disk access faster. It will be quite efficient if we read the data in
bigger
chunks i.e. 64k or 256k bytes and also write in bigger chunks. Today’s operating
system
applies the buffering and similar techniques. Instead of reading and writing character-bycharacter
or word-by-word, reading and writing line by line is efficient. A function is
available for this purpose i.e.
getLine() for input file
stream and putLine()
for output file
stream. The syntax of getLine()
is as follows:
Deleted: and that is
Deleted: file we
Deleted: file then
Deleted: put(),
so
Deleted: Whenever we declare
Deleted: like if
Deleted: i;
we
Deleted: 0;
Deleted: efficiency, but do not sacrifice
the clarity for
Deleted: device and
Deleted: which is
Deleted: Although nowadays
Deleted: read
Page 216
char name[100];
int maxChar = 100;
int stopChar = ‘o’;
inFile.getLine(name, maxChar, stopChar);
The first argument is a character
array. The array should
be large enough to hold the
complete line. The second argument is the maximum number of characters to be read.
The third one is the character if we want to stop somewhere. Suppose we have an
input
file containing the line ‘Hello World’, then the statements:
char str[20];
inFile.getLine(str, 20, ‘W’);
cout << “The line read from the input file till W is ” << str;
The getLine() function
will read ‘Hello ’. Normally we do not use the third argument.
The default value for the third argument is new line character so
getLine() will read the
complete line up to the new line character. The new line character will not be read.
The
line read will be stored in the array, used in the first argument. It is our responsibility
that
the array should be large enough to hold the entire
line. We can manipulate
this data.
Using the getLine()
repeatedly to read the file is much more efficient rather than using the
get() function. As the
getLine() function does
not read the new line character, we have to
put it explicitly. If we have large file to be read, the difference in speed with
both the
programs i.e. using get()
and getLine()
can be noted.
Exercise:
Write a program which reads a file using the getLine() function and display it on
the
screen.
Sample input file:
This is a test program
In this program we learn how to use getLine() function
This function is faster than using the get() function
The complete code of the program:
/*
* This program reads from a txt file line by line
*
*/
#include <iostream.h>
#include <fstream.h>
main()
{
ifstream inFile; // Handle for the input file
Deleted: array, the
Deleted: which is
Deleted: line and then we
Deleted: then
Page 217
char inputFileName[] = "test.txt"; // file name, this file is in the current directory
const int MAX_CHAR_TO_READ = 100; // maximum character to read in one line
char completeLineText[MAX_CHAR_TO_READ]; // to be used in getLine function
inFile.open(inputFileName); // Opening the file
// checking that file is successfuly opened or not
if (!inFile)
{
cout << "Can't open input file named " << inputFileName << endl;
exit(1);
}
// Reading the complete file line by line and printing on screen
while (!inFile.eof())
{
inFile.getline(completeLineText, MAX_CHAR_TO_READ);
cout << completeLineText << endl;
}
inFile.close();
}
The output of the program is:
This is a test program
In this program we learn how to use getLine() function
This function is faster than using the get() function
Example 2
Problem statement:
A given input file contains Name of the employee and salary of current month. There
is a
single space between the name and the salary. Name and salary can not contain spaces.
Calculate the total salaries of the employees. Create an output file and write the
total
salary in that file.
Solution:
We can read a line from the input file using the
getLine() function. Now
we need to break
this line into pieces and get the name and salary in different variables. Here we
can use
the string token function i.e.
strtok(). The string token
function (strtok()) takes a string
and a delimiter i.e. the character that separates tokens from each other. As there
is a space
between the name and the
salary, we can use the
space character as delimiter. So the first
call to the string token function will return the name of the employee, the second
call will
return the salary of the employee. The syntax to get the next token from the
strtok()
function is: strtok(NULL, ‘
‘).It means return the
next token from the same string. The
Deleted: salary so
Deleted: ‘), it
Page 218
second token contains the salary of the employee and is in a char string. We need
to add
the salaries of all the employees. So convert the salary from character to integer.
For this
purpose we can use atoi()
function.
Sample input file:
Aamir 12000
Amara 15000
Adnan 13000
Afzal 11500
Complete code of the program:
/*
* This program reads name and salary from a txt file
* Calculate the salaries and write the total in an output file
*/
#include <iostream.h>
#include <fstream.h>
#include <cstring>
#include <cstdlib>
main()
{
ifstream inFile; // Handle for the input file
char inputFileName[] = "salin.txt"; // file name, this file is in the current directory
ofstream outFile; // Handle for the output file
char outputFileName[] = "salout.txt"; // file name, this file is in the current
directory
const int MAX_CHAR_TO_READ = 100; // maximum character to read in one line
char completeLineText[MAX_CHAR_TO_READ]; // used in getLine function
char *tokenPtr; // Used to get the token of a string
int salary, totalSalary;
salary = 0;
totalSalary = 0;
inFile.open(inputFileName); // Opening the input file
outFile.open(outputFileName); // Opening the output file
// Checking that file is successfully opened or not
if (!inFile)
{
cout << "Can't open input file named " << inputFileName << endl;
exit(1);
}
if (!outFile)
{
Deleted: so we need
Page 219
cout << "Can't open output file named " << outputFileName << endl;
exit(1);
}
// Reading the complete file line by line and calculating the total salary
while (!inFile.eof())
{
inFile.getline(completeLineText, MAX_CHAR_TO_READ);
tokenPtr = strtok(completeLineText, " "); // First token is name
tokenPtr = strtok(NULL, " "); // 2nd token is salary
salary = atoi(tokenPtr);
totalSalary += salary;
}
// Writing the total into the output file
outFile << "The total salary = " << totalSalary;
// closing the files
inFile.close();
outFile.close();
}
The contents of output file:
The total salary = 51500
Exercise:
1) Modify the above program such that the input and output files are given as the
command line arguments. Add another information in the input file i.e. the
age of the employee. Calculate the average age of the employees and write it
in the out put file.
2) Write a program, which reads an input file. The structure of the input file is
First Name, Middle Initial, Last Name. Create an output file with the structure
First Name, Login Name, Password. First name is same as in the input file.
The login name is middle initial and last name together. The password is the
first four digits of the first name. First name, middle initial and last name does
not contain space.
The sample input file is:
Syed N Ali
Muhammad A Butt
Faisal A Malik
Muhammad A Jamil
If the above file is used as input, the output should be as follows:
Syed Nali Syed
Muhammad Abutt Muha
Page 220
Faisal Amalik Fais
Muhammad Ajamil Muha
Tips
• Always close the file with the close function.
• Open a file explicitly with open function
• Always apply the error checking mechanism while handling with files.
|
|
|
|