ZeePedia Add to Favourites   |   Contact us


Introduction to Programming

<<< Previous Files: Text File Handling, Output File Handling Next >>>
 
img
CS201 ­ Introduction to Programming
Lecture Handout
Introduction to Programming
Deleted: Handout
Lecture No. 18
Deleted: Lecture No. 18
Reading Material
Chapter 14
Deitel & Deitel - C++ How to Program
Deleted: Chapter. 14
14.3, 14.4, 14.5, 14.6
Summary
1)
Files
2)
Text File Handling
Deleted: Example 1
3)
Example 1
Deleted: Example 2
4)
Output File Handling
Deleted: Today's topic is about
5)
Example 2
Deleted: handling. We have been
6)
Tips
talking about
Deleted: Then we discuss
Deleted: When we combine all these
things, it
Files
Deleted: We type
We will discuss files and file handling in this lecture. The topic is going to be a sequel of
Deleted: processor. Similarly, we can
the subjects like bit, bytes, character, numbers etc. In the previous lecturers, we have
have essays, novels as a
talked about strings, which are actually character arrays. These all the subjects when
Deleted: bigger collection of words,
sentences. These are no longer bits and
combined together, becomes a program. While typing a letter or a document in word
bytes. We call these
processor, we actually deal with big collection of words like sentences, not with bits and
Deleted: sentences, paragraph as files.
bytes. These combinations of characters, words, sentences and paragraph are called as
There are many types of files in the
files. The files in the computer are classified under different categories. Primarily, there
computer. Primarily
are two types of files i.e. text files and executable program files. Text files consist of
Deleted: The other type is executable
programs, which runs on
readable English characters. These include our simple text files, or word processor file
Deleted: issue
etc. On the other hand, the executable program files run the program. In the dos
Deleted: windows, click
(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
Deleted: Files can contain data or there
are program files.
see the list of the files in that folder in the right panel. These are the names of the files,
Deleted: note pad,
which we see. The file properties show the length of the file, date of creation etc. One
Deleted: meaning
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
Deleted: involves and we
formatting of text involved. We can view this text using the `type' command of the dos
Deleted: Today we will be discussing
plain text files
(type filename). Similarly, our source programs are also plain text files. There is no
Deleted: are
formatted text in cpp files. There is another kind of text files, which are not plain ones.
Deleted: text files.
Page 207
img
CS201 ­ Introduction to Programming
These are the word processor files, containing text that is formatted like, bold, italic,
Deleted: files. These files contain text
but this text
underline, colored text and tables. This formatting information is also stored in the file
Deleted: text, therefore
along with the text. Therefore such files are not plain text files. Same thing applies to
Deleted: on spreadsheets, which
spreadsheets having formatting, formulae, cell characteristic etc. Though these files
contain
contain some binary information along with the text, yet these are not program files. We
Deleted: formulas,
created these files using some other program like Microsoft Word, excel etc. Such files
Deleted: but
also fall in the category of text files. The other type is the program file that executes on
Deleted: lie
the computer. Normally, executable files contain only non-printable binary information.
There are different ways of handling these files.
Deleted: s
Today we will see what is the utility of files in our programs. We know that all the
Deleted: binary information, which is
not printable.
information in the computer memory is volatile. It means when we turn off the computer
Deleted:
that information will be lost. The data, written in a program, is actually the part of the
So far, we have been using characters,
program and is saved on the disk. Whenever we execute the program that data will be
numbers in our program. Then we learn
how to use arrays and strings, which are
available. Suppose we have to develop a payroll system for a factory. For this purpose,
actually character arrays. Today we will
we will at first need to gather the data like name of the employees, their salaries etc.
learn how to use files in the program. The
question arises why we want to use
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
Deleted: which is
question arises whether we will have to enter the name and salary of employees every
Deleted: the program is
month. The better way is to store this information once and re-use it every month. We can
Deleted: is
save this information in a file and can calculate the salary after getting the current
Deleted: Now suppose
month's attendance of employees. We have to do all the calculations again in case of not
Deleted: First
saving the report on the disk. It will be nicer if we have saved the output file on the disk.
Deleted: employees, their salary etc.
We can take the print out whenever we need. We are discussing this just to give you the
Enter all this information, then get their
attendance, and then calculate their
justification of using files. The data in the memory is volatile. Similarly, the data, which
salary. Finally print a report of their
we key in the program during the execution of a program, is also volatile. To save the
salary. Are we going
data on permanent basis, we need files so that we keep these on the disk and can use
Deleted: month?
whenever needed. Now there is need to learn how to create a file on the disk, read from
Deleted: then by
the file, and write into the file and how to manipulate the data in it. This is the file
Deleted: employees can calculate the
handling.
salary. Similarly, do we need to save.. [1]
. the
Deleted: again, if we did not save
Text file Handling
Deleted: disk, we
Let's see what are the basic steps needed for file handling. Suppose we have a file on the
Deleted: feel for the
disk and want to open it. Then read from or write into the file before finally closing it.
Deleted: files
The basic steps of file handling are:
Deleted: we needed. So we have
Deleted: the file.
Open the file
Deleted: Today we will discuss text file
... [2]
Read and write
Deleted: Lets look
Close the file
Deleted: we need
Deleted: disk. First we need to open [3]
...
We have been using cin and cout a lot in the programs. We know that these are the doors
Deleted: and then finally close the file.
by which data can enter and come out. cin is used to enter the data and cout is used to
Deleted: our
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
Deleted: C++
about file handling. This is how 'C++ language' handles files. For this purpose, the
Deleted: and not C
header file to be used is <fstream.h> (i.e. file stream). Whenever using files in the
Deleted: we are
program, we will include this header file as #include <fstream.h>. These streams are
Deleted: our
Page 208
img
CS201 ­ Introduction to Programming
used the way we have been employing cin and cout but we can do more with these
Deleted: in similar way we have been
using cin and
streams. While handling files, one can have three options. Firstly, we will only read the
Deleted: cout, but we can do more with
file i.e. read only file. It means the file is used as input for the program. We need to have
these streams. Now we
a stream for input file i.e. ifstream (input file stream). Similarly, if we want to write in
Deleted: First option is
some file, ofstream (output file stream) can be used. Sometimes we may need to read and
Deleted: and that stream is
write in the same file. One way is to read from a file, manipulate it and write it in another
Deleted: need
file, delete the original file and renaming the new file with the deleted file name. We can
Deleted: we will use
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
Deleted: Let us take a look
fstream.h in our programs. Then we need to declare file streams. cin and cout are pre-
Deleted: predefined streams therefore
we did not declare these.
defined 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
Deleted: handle to refer
variables, used to handle the files that are on the disk. We will use inFile as declared
Deleted: variables which will be
above to read a file. Any meaningful and self-explanatory name can be used. To deal
Deleted: disk. If we want to read a file,
with a payroll system, payrollDataFile can be used as a file stream variable i.e. ifstream
we
payrollDataFile;. Consider the following statement:
Deleted: above. We can use any name
here, which is meaningful and self-
explanatory. Suppose if
ifstream myFile;
Deleted: system, we can declare a
Deleted: as:
Here myFile is an internal variable used to handle the file. So far, we did not attach a file
Deleted: variable, which will be used o
with this handle. Before going for attachment, we will have to open a file. Logically,
Deleted: First, we need to open a file
there is function named `open' to open a file. While associating a file with the variable
and logically
myFile, the syntax will be as under:
Deleted: How can we use the open
function? As we want to associate
myFile.open(filename);
Deleted: myFile. The syntax is as;
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
Deleted: and
of ifstream. The argument for the open function filename is the name of the file on the
Deleted: , this
disk. The data type of argument filename is character string, used to give the file name in
Deleted: can
double quotation marks. The file name can be simple file name like "payroll.txt". It can
Deleted: or it
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
Deleted: etc and we
like `myprogs' and can have files in this folder. The fully qualified path means that we
have to give the path beginning from C:\.
Deleted: starting from C:\. There is
another short hand for this. If
To under stand it further, suppose that we are working in the folder `myprogs' and our
Deleted: In this case,
source and executable files are also in this folder. Here, we don't need to give a complete
Deleted: the
path and can write it as "payroll.txt". If the file to be opened is in the current directory
Deleted: folder) then we
(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
Deleted: its
from windows help system. It is a hierarchical system. The disk, which is at the top,
Deleted: hierarchal system. At the top
is disk, which
Page 209
img
CS201 ­ Introduction to Programming
contains folder and files. Folders can contain subfolders and files. It is a multi-level
Deleted: It's a multilevel hierarchal
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
Deleted: bottom up tree, root
downward. Here `root' is considered as root of a tree and files or subfolders are branches.
Deleted: and
To open a file, we use open function while giving it the name of the file as fully qualified
Deleted: and give
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
Deleted: time, it mean whenever it
encounters a space
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
Deleted: Lets take
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:
Page 210
img
CS201 ­ Introduction to Programming
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
Deleted: Below are
Deleted: and a sample
Let's write a simple program, which will read from a file `myfile.txt' and print it on the
Deleted: Name  Salary Department
screen. "myfile.txt" contains employee's name, salary and department of employees.
Aamir 12000 Sales
Following is the complete program along with "myfile.txt" file.
Amara 15000 HR
Adnan 13000 IT
Afzal 11500 Marketing
... [4]
Sample "myfile.txt".
Deleted: /*
Name Salary Department
* This program reads from a txt file
"myfile.txt" which contains the
Aamir 12000 Sales
* employee information
Amara 15000 HR
*/
Adnan 13000 IT
#include <iostream.h>
Afzal 11500 Marketing
#include <fstream.h>
main()
Code of the program.
{
ifstream inFile;
//
/*
Handle for the input file
* This program reads from a txt file "myfile.txt" which contains the
char inputFilename[] = "myfile.txt";
// file name, this file is in the current
* employee information
directory
*/
inFile.open(inputFilename);
// OPening the file
#include <iostream.h>
// checking that file is successfuly
opened or not
#include <fstream.h>
if (!inFile)
{
cout << "Can't open input file named "
main()
exit(1);
<< inputFilename << endl;
{
}
char name[50];
// used to read name of employee from file
char name[50];  // used to read name
char sal[10];
// used to read salary of employee from file
of employee from file
char sal[10];
// used to read salary
char dept[30];
// used to read dept of employee from file
of employee from file
ifstream inFile;
// Handle for the input file
char dept[30];  // used to read dept of
employee from file
// Reading the complete file word by
char inputFileName[] = "myfile.txt";
// file name, this file is in the current directory
word and printing on screen
while (!inFile.eof())
{
inFile.open(inputFileName);
// Opening the file
inFile >> name >> sal >> dept;
cout << name << "\t" << sal << " \t"
<< dept << endl;
// checking that file is successfully opened or not
}
inFile.close();
}
... [5]
Page 211
img
CS201 ­ Introduction to Programming
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();
}
Deleted: Name  Salary Department
Output of the program.
Aamir 12000 Sales
Name Salary Department
Amara 15000 HR
Adnan 13000 IT
Aamir  12000 Sales
Afzal 11500 Marketing
... [6]
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()
Deleted: directory, as we have not
given the
function. After opening the file, we will check that file is successfully opened or not. If
Deleted: are checking
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
Deleted: Then we are reading
file and put it into the variables. The condition in `while loop' is "!inFile.eof()" means
Deleted: ting
until the end of file reached. The function eof() returns true when we reached at the end
Deleted: while loop
of file.
Output File Handling
Deleted: We
Let's talk about the output file handling. You can do several things with output files like,
Deleted: files. We may want to create
creation of a new file on the disk and writing data in it. Secondly, we may like to open an
Deleted: write
existing file and overwrite it in such a manner that all the old information is lost from it
Deleted: want
and new information is stored. Thirdly, we may want to open an existing file and append
Deleted: will be
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
Deleted: write new information.
options and we might use any one of these methods. All these things are related to the
Deleted: we may want to open
file-opening mode. The actual syntax of open function is:
Deleted: and want to modify it such
that can write
open (filename, mode)
Deleted: be interested in using
Deleted: the option.
Deleted: file opening
Page 212
img
CS201 ­ Introduction to Programming
The first argument is the name of the file while the second will be the mode in which file
Deleted: and
is to be opened. Mode is basically an integer variable but its values are pre-defined.
Deleted: argument is
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)
Deleted: out
... [7]
out
Open a file or stream for insertion (output)
Deleted: in
... [8]
app
Append rather than truncate an existing file. Each insertion
(output) will be written to the end of the file
Deleted: trunc
... [9]
trunc
Discards the file's contents if it exists. (similar to default
behavior)
Deleted: ate
... [10]
ate
Opens the file without truncating, but allows data to be
written anywhere in the file
Deleted: binary
... [11]
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
Deleted: will be
want to append into the file, the mode will be ios::app. When we write into the file, it
Deleted: file then the mode is ios::app,
and when
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
Deleted: there, it
mode. But in `ate mode' we can write anywhere in the file. With the trunc mode, the file
Deleted: mode but in ate mode
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>
Page 213
img
CS201 ­ Introduction to Programming
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
Deleted: employees i.e.
"employeein.txt", add
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
Deleted: We have
to read from the file. The get() function is used to get a character from the file, so that we
Deleted:
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
Deleted: it is also
will be as:
Page 214
img
CS201 ­ Introduction to Programming
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
Deleted: and that is
output file we have to insert the new line character explicitly, whereas get() function
Deleted: file we
reads each character as it was typed. So if we have to make a copy of a file, the function
Deleted: file then
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
Deleted: put(), so
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
Deleted: Whenever we declare
initialize it as i = 0. Similarly we can declare and initialize an input or output file stream
Deleted: like if
variable as:
Deleted: i; we
Deleted: 0;
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
Deleted: efficiency, but do not sacrifice
the clarity for
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
Deleted: device and
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
Deleted: which is
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
Deleted: Although nowadays
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
Deleted: read
applies the buffering and similar techniques. Instead of reading and writing character-by-
character 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:
Page 215
img
CS201 ­ Introduction to Programming
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
Deleted: array, 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
Deleted: which is
the array should be large enough to hold the entire line. We can manipulate this data.
Deleted: line and then we
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
Deleted: then
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
Page 216
img
CS201 ­ Introduction to Programming
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
Deleted: salary so
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: `), it
Page 217
img
CS201 ­ Introduction to Programming
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
Deleted: so we need
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)
{
Page 218
img
CS201 ­ Introduction to Programming
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 219
img
CS201 ­ Introduction to Programming
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.
Page 220
Table of Contents:
  1. What is programming
  2. System Software, Application Software, C language
  3. C language: Variables, Data Types, Arithmetic Operators, Precedence of Operators
  4. C++: Examples of Expressions, Use of Operators
  5. Flow Charting, if/else structure, Logical Operators
  6. Repetition Structure (Loop), Overflow Condition, Infinite Loop, Properties of While loop, Flow Chart
  7. Do-While Statement, for Statement, Increment/decrement Operators
  8. Switch Statement, Break Statement, Continue Statement, Rules for structured Programming/Flow Charting
  9. Functions in C: Structure of a Function, Declaration and Definition of a Function
  10. Header Files, Scope of Identifiers, Functions, Call by Value, Call by Reference
  11. Arrays: Initialization of Arrays, Copying Arrays, Linear Search
  12. Character Arrays: Arrays Comparisonm, Sorting Arrays Searching arrays, Functions arrays, Multidimensional Arrays
  13. Array Manipulation, Real World Problem and Design Recipe
  14. Pointers: Declaration of Pointers, Bubble Sort Example, Pointers and Call By Reference
  15. Introduction, Relationship between Pointers and Arrays, Pointer Expressions and Arithmetic, Pointers Comparison, Pointer, String and Arrays
  16. Multi-dimensional Arrays, Pointers to Pointers, Command-line Arguments
  17. String Handling, String Manipulation Functions, Character Handling Functions, String Conversion Functions
  18. Files: Text File Handling, Output File Handling
  19. Sequential Access Files, Random Access Files, Setting the Position in a File, seekg() and tellg() Functions
  20. Structures, Declaration of a Structure, Initializing Structures, Functions and structures, Arrays of structures, sizeof operator
  21. Bit Manipulation Operators, AND Operator, OR Operator, Exclusive OR Operator, NOT Operator Bit Flags Masking Unsigned Integers
  22. Bitwise Manipulation and Assignment Operator, Programming Constructs
  23. Pre-processor, include directive, define directive, Other Preprocessor Directives, Macros
  24. Dynamic Memory Allocation, calloc, malloc, realloc Function, Dangling Pointers
  25. History of C/C++, Structured Programming, Default Function Arguments
  26. Classes and Objects, Structure of a class, Constructor
  27. Classes And Objects, Types of Constructors, Utility Functions, Destructors
  28. Memory Allocation in C++, Operator and Classes, Structures, Function in C++,
  29. Declaration of Friend Functions, Friend Classes
  30. Difference Between References and Pointers, Dangling References
  31. Operator Overloading, Non-member Operator Functions
  32. Overloading Minus Operator, Operators with Date Class, Unary Operators
  33. Assignment Operator, Self Assignmentm, Pointer, Conversions
  34. Dynamic Arrays of Objects, Overloading new and delete Operators
  35. Source and Destination of streams, Formatted Input and Output, Buffered Input/Output
  36. Stream Manipulations, Manipulators, Non Parameterized Manipulators, Formatting Manipulation
  37. Overloading Insertion and Extraction Operators
  38. User Defined Manipulator, Static keyword, Static Objects
  39. Pointers, References, Call by Value, Call by Reference, Dynamic Memory Allocation
  40. Advantages of Objects as Class Members, Structures as Class Members
  41. Overloading Template Functions, Template Functions and Objects
  42. Class Templates and Nontype Parameters, Templates and Static Members
  43. Matrices, Design Recipe, Problem Analysis, Design Issues and Class Interface
  44. Matrix Constructor, Matrix Class, Utility Functions of Matrix, Input, Transpose Function
  45. Operator Functions: Assignment, Addition, Plus-equal, Overloaded Plus, Minus, Multiplication, Insertion and Extraction