Docsity

Text File Handling-Introduction To Programming-Lecture Notes, Study notes of Computer Programming

Toggle sidebar
bg1
198
8
eadin
Lecture No. 1
g MaterialR
Deitel & Deitel - C++ How to Program Chapter 14
14.3, 14.4, 14.5, 14.6
Summary
Files
Text File Handling
Example 1
Output File Handling
Example 2
Tips
Files
Today’s topic is about files and file handling. We have been talking about bit, bytes,
character, numbers etc. Then we discuss about strings, which are actually chara
rrays. When we combine a
cter
ll these things, it becomes a program. We type a letter or a
ilarly, we can have a novel as a combinations of
words and sentences. These are no
es, paragraphs as files. There are many
splayed. Similarly, Windows
ows, click on some folder to see the list of the files in that
ese are the names of the files, which we see. The file
ory of data files is
e pad, type the
s no formatting of text
text using the ‘type’ command of the dos (type
, our source programs are also plain text files. There is no
which are not plain
nes. T ese ar formatted like, bold,
alic, underline, colored text and tables. This formatting information is also stored in
xt. Therefore such files are not plain text files. Same thing
Word,
puter. Normally, executable files contain only
ation. There are different ways of handling these files.
e utility of files in our programs. We know that all the
puter memory is volatile. It means when we turn off the
ation will be lost. The data, written in a program, is actually the
sk. Whenever we execute the program that
a
document in word processor. Sim
characters, words, sentences, bigger collection of
onger bits and bytes. We call these sentencl
types of files in computer. 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),
hen we issue the command ‘dir’, a list of files is diw
explorer is used in the wind
t panel. Thfolder in the righ
properties show the length of the file, date of creation etc. One categ
ndows notplain text files. We can create plain text files using the wi
ry text, meaning that there itext and save it. It is an ordina
involved and we can view this
filename). Similarly
ormatt d text f e in cpp files. There is another kind of text files,
h e the word processor files, containing text that iso
it
the file along with the te
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
xcel etc. Such files also fall in the category of text files. The other type is thee
program file that executes on the com
non-printable binary inform
Today we will see what is th
information in the com
computer that inform
part of the program and is saved on the di
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Text File Handling-Introduction To Programming-Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!

eadin

Lecture No. 1

R g Material

Deitel & Deitel - C++ How to Program Chapter 14 14.3, 14.4, 14.5, 14.

Summary Files Text File Handling Example 1 Output File Handling Example 2 Tips

Files Today’s topic is about files and file handling. We have been talking about bit, bytes, character, numbers etc. Then we discuss about strings, which are actually chara rrays. When we combine a

cter ll these things, it becomes a program. We type a letter or a ilarly, we can have a novel as a combinations of words and sentences. These are no es, paragraphs as files. There are many

splayed. Similarly, Windows ows, click on some folder to see the list of the files in that ese are the names of the files, which we see. The file ory of data files is e pad, type the s no formatting of text text using the ‘type’ command of the dos (type , our source programs are also plain text files. There is no which are not plain nes. T ese ar formatted like, bold, alic, underline, colored text and tables. This formatting information is also stored in xt. Therefore such files are not plain text files. Same thing

Word,

puter. Normally, executable files contain only ation. There are different ways of handling these files. e utility of files in our programs. We know that all the puter memory is volatile. It means when we turn off the ation will be lost. The data, written in a program, is actually the sk. Whenever we execute the program that

a document in word processor. Sim characters, words, sentences, bigger collection of longer bits and bytes. We call these sentenc types of files in computer. 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 issue the command ‘dir’, a list of files is di explorer is used in the wind folder in the right panel. Th properties show the length of the file, date of creation etc. One categ plain text files. We can create plain text files using the windows not text and save it. It is an ordinary text, meaning that there i involved and we can view this filename). Similarly formatt d text e in cpp files. There is another kind of text files, o h e the word processor files, containing text that is it the file along with the te 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 excel etc. Such files also fall in the category of text files. The other type is the program file that executes on the com non-printable binary inform Today we will see what is th information in the com computer that inform part of the program and is saved on the di

docsity.com

ata will be available. Suppose we have to develop a payroll system for a factory. For t first need to gather the data like name of the employees, their ries etc. Enter all this information before getting their attendance. After collecting the salary. Now r 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 look what are the basic steps we need 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 our 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 our program, we will include this header file as #include <fstream.h>. These streams are 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 us take a look 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 therefore we did not declare these. We can declare file stream as:

ifstream inFile; // object for reading from a file ofstream outFile; // object for writing to a file

d this purpose, we will a sala all the information, you can calculate their salary and print a report of the question arises whethe

docsity.com

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, 2 nd^ 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.

Lets take 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 pe s is successful. We can write as:

if (!myFile)

here is some error opening file” << endl; << “ File cannot be opened” << end; exit(1);

ut << “ File opened successfully “ << end;

d print it on xt” contains employee’s name, salary and department of mployees. Following is the complete program along with “myfile.txt” file.

Department Sales R

Marketing

the handle of the file. Therefore, before going ahead, we have to make sure that file o ning proces

cout << “T cout

} else co

Example 1 Let’s write a simple program, which will read from a file ‘myfile.txt’ an the screen. “myfile.t e

Sample “myfile.txt”. Name Salary Aamir 12000 Amara 15000 H Adnan 13000 IT Afzal 11500

docsity.com

gram.

reads from a txt file “myfile.txt” which contains the rmation

char name[50]; // used to read name of employee from file // used to read salary of employee from file of employee from file ; // Handle for the input file

"; // file name, this file is in the current directory

inFile.open(inputFileName); // Opening the file

g the complete file word by word and printing on screen

inFile >> name >> sal >> dept;

Code of the pro /*

  • This program
  • employee info */

#include <iostream.h> #include <fstream.h>

main() {

char sal[10]; char dept[30]; // used to read dept ifstream inFile

char inputFileName[] = "myfile.txt

// checking that file is successfully opened or not if (!inFile) { cout << "Can't open input file named " << inputFileName << endl; exit(1); }

// Readin while (!inFile.eof()) {

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

docsity.com

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>

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

docsity.com

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:

char c; while ( (c = inFile.get()) != EOF) { // do all the processing outFile.put(c); }

There is one limitation with the ‘>>’ and that is 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.

Whenever we declare a variable we initialize it like if 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 and 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

docsity.com

#include <iostream.h> #include <fstream.h>

main() { ifstream inFile; // Handle for the input file 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

docsity.com

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 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 we need to 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 #include

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) { cout << "Can't open output file named " << outputFileName << endl;

docsity.com

Open a file explicitly with open function Always apply the error checking mechanism while handling with files.

docsity.com