HowToProgramC : Lesson 32


Back Home Next



Input File Handling

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 understand 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, 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:

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 Code

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

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.



Back Home Next


Google




learntoknow@yahoo.com
© All rights Reserved.