File Handling
File Handling
cin and cout are stream in C++by which data can enter
and come out.
cin is used to enter the data
cout is used to display the data on the screen.
More streams are available for file handling
For this, header file to be used is <fstream.h>
These streams are used the way we have been employing
cin and cout but we can do more with these streams.
Introduction
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:
File Handling(Reading)
char c;
while ( (c = inFile.get()) != EOF)
{
// do all the processing
outFile.put(c);
}
File Handling(Reading)
main()
{
ifstream infile; // Handle for the input file
char outputFileName[]="d:/Dicitionary.txt"; // The file is created
infile.open(outputFileName,ios::in); // Opening the file
char c;
while((c=infile.get())!=EOF)
{
cout<<c;
}
infile.close();
getch();
}
Copying a File (Reading and writing)
main()
{
ifstream infile; // Handle for the input file
ofstream outfile;
char inputFileName[]="d:/Dicitionary.txt";
char outputFileName[]="d:/abc.txt";
infile.open(inputFileName,ios::in);
outfile.open(outputFileName,ios::out); // Opening the file
char c;
while((c=infile.get())!=EOF)
outfile<<c;
infile.close();
outfile.close();
getch();
File Reading line by line
We can initialize the file directly
ifstream inFile(“myFileIn.txt”);
ofstream outFile(“myfileOut.txt”, ios::out);
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.
File Reading line by line
tokenptr=strtok(NULL," ");
File Handling
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”.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
main()
{
ifstream infile;
ofstream outfile;
infile.open("d:/salin.txt", ios::in);
outfile.open("d:/salout.txt", ios::out);
int sal, totalsal;
sal=0;
totalsal=0;
char *tokenptr;
char completelinetext[100];
while(!infile.eof())
{
infile.getline(completelinetext,100);
tokenptr=strtok(completelinetext," ");
outfile<<tokenptr<<" ";
tokenptr=strtok(NULL," ");
sal=atoi(tokenptr)+2000;
outfile<<sal<<endl;
}
infile.close();
Exercise Problem
By writing:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
main()
{
long pos;
ifstream infile;
infile.open ("d:/salin.txt");
infile.seekg(-20, ios::end);
char c;
while((c=infile.get())!=EOF)
cout<<c;
infile.close();
getch();
}
Moving in a File