2. Many real life problems handle large volume of data and in
such situation we need to use some devices such as floppy
disk or hard disk to store data.
The data is stored in these devices using the concept of
file.
A File is a collection of related data stored in a particular
area on the disk.
Program can be designed to perform the read and write
operations on these files.
The program can be involves either or both kind of data
communications:
a. Data transfer between the console unit and the
program.
b. Data transfer between the program and the disk file.
By Hansa Halai
3. The I/O System of c++ handles the file operations which
is very much similar to the console input and output
operation.
It uses file stream as an interface between the
program and the files.
The stream that supplies data to program is known as
input stream.
The stream that receives data from the program is
known as output stream.
In other word, the input stream extracts (or read) data
from file and the output stream insert (or write) data to
file.
By Hansa Halai
5. CLASSES FOR FILE STREAM OPERATION:
There are three file I/O classes used for read/write
operations:
ifstream: can be used to read operations.
ofstream: can be used to write operations.
fstream: can be used for both read and write
operations.
fstreambase: serves as base for fstream,
ofstream, ifstream.
By Hansa Halai
7. OPENING AND CLOSING FILE:
If we want to use a disk file, we need to decide the
following things about the file and its intended use:
1. Suitable name for the file.
2. Data type and structure.
3. Purpose.
4. Opening method.
For opening, we must first create a file stream and
then link it to the filename. A file stream can be
defined using the classes ifstream, ofstream and
fstream that are contain in the header file fstream.
A file can be opened in two ways:
1. Using the constructor function of the class.
2. Using the method function open() of the class.
By Hansa Halai
8. The first method is useful when we use only one file in the stream.
The second method is used when we want to manage multiple file
using one stream.
Opening file using constructor:
As we know that a constructor is used to initialize an object while
it is being created. here, a file name is used to initialize the file
stream object.
This involves following steps:
1. Create a file stream object to manage the stream using the
appropriate class. That is to say, the class ofstream is used to
create the output stream and ifstream to create the input
stream.
2. Initialize the file object with the desired filename.
For Ex: ofstream outfile(“file1”);
By Hansa Halai
10. EXAMPLE:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outf("ITEM"); //connect item file to outf
cout<<"Enter Item name: ";
char name[10];
cin>>name;
outf<<name<<"n"; //write in file ITEM
cout<<"Enter Item cost: ";
float price;
cin>>price;
outf<<price<<"n";
By Hansa Halai
11. outf.close();
ifstream inf("ITEM");
inf>>name; // read name from file
inf>>price;
cout<<"n";
cout<<"Item Name: "<<name<<"n";
cout<<"Item Price: "<<price<<"n";
inf.close();
return 0;
}
By Hansa Halai
Read data from file.
The created file is stored in a place
where the program is saved.
12. OPENING FILE USING OPEN() METHOD:
The open() function is used to open multiple files that use the same
stream object.
Syntax:
file_stream_class stream_object;
stream_object.open(“filename”);
Ex:
ofstream ofile;
ofile.open(“file1”);
…
…
ofile.close();
ofile.open(“file2”);
…
…
ofile.close();
By Hansa Halai
13. Note that the first file is closed before the second file is open.
This is necessary because a stream can be connected to only
one file at a time.
Example:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream file1_out;
file1_out.open("Country");
file1_out<<"India"<<endl;
file1_out<<"UK"<<endl;
file1_out<<"USA"<<endl;
file1_out.close();
By Hansa Halai
16. READING FROM TWO FILES SIMULTANEOUSLY:
Example:
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
const int size = 50;
char line[size];
ifstream fin1,fin2;
fin1.open("country");
fin2.open("capital");
By Hansa Halai
17. for(int i=1;i<=3;i++)
{
if(fin1.eof()!=0)
{
cout<<"Exit from country file..n";
exit(1);
}
fin1.getline(line,size);
cout<<"nCapital of "<<line<<endl;
if(fin2.eof()!=0)
{
cout<<"nExit from capital file..";
exit(1);
}
fin2.getline(line,size);
cout<<" "<<line<<"n";
}
return 0;
}
By Hansa Halai
18. DETECTING END-OF-FILE:
Detection of the end-of-file condition is necessary for
preventing any further attempt to read data from the file.
We can achieve this by using following two statement:
1) while (file_stream_object)
Ex: while(fin)
The while loop terminates when fin object returns a value
of zero or reaching at the end-of-file.
2) if(fin.eof()!=0)
{
exit(1);
}
The eof() is a member function of ios class. It returns a non-
zero value if the end-of-file condition encountered. Therefore ,
the statement terminates the program on reaching the end of
file.
By Hansa Halai
19. FILE MODES:
We have used ifstream and ofstream constructor and
open() method to create a new file or open a existing file.
By Hansa Halai
File Type Default Open Mode
ofstream
The file is opened for output only. (Information may be
written to the file, but not read from the file.) If the file does
not exist, it is created. If the file already exists, its contents
are deleted (the file is truncated).
ifstream
The file is opened for input only. (Information may be
read from the file, but not written to it.) The file’s contents
will be read from its beginning. If the file does not exist, the
open function fails.
20. In both these methods, we used only one argument list that was
file name.
open() can also take two arguments, the second one
specifying the file mode.
syntax:
stream_object.open(“file_name”,mode);
Ex:
fout.open(“student”,ios::out) ;
The prototype of these class member functions contains default
value for second argument and therefore they use the default
value in absence of the actual values. The default values as
follows:
ios::in – For ifstream function meaning open for reading only.
ios::out – For ofstream function meaning open for writing only.
By Hansa Halai
21. By Hansa Halai
File Mode Flag Meaning
ios::app
Append mode. If the file already exists, its contents are
preserved and all output is written to the end of the file. By
default, this flag causes the file to be created if it does not
exist.
ios::ate
If the file already exists, the program goes directly to
the end of it. Output may be written anywhere in the file.
ios::binary
Binary mode. When a file is opened in binary mode,
information is written to or read from it in pure binary format.
(The default mode is text.)
ios::in
Input mode. Information will be read from the file. If the
file does not exist, it will not be created and the open
function will fail.
22. By Hansa Halai
File Mode
Flag
Meaning
ios::nocreate If the file does not already exist,
this flag will cause the open function
to fail. (The file will not be
created.)
ios::noreplace If the file already exists, this flag
will cause the open function to fail.
(The existing file will not be
opened.)
ios::out Output mode. Information will be
written to the file. By default, the
file’s contents will be deleted if it
already exists.
ios::trunc If the file already exists, its
contents will be deleted (truncated).
This is the default mode used by
ios::out.
23. FILE POINTER AND THEIR MANIPULATIONS:
Each file has two associated pointer known as the file
pointers. one of them is called input pointer or get
pointer and other is called the output pointer or put
pointer.
The input pointer is used for reading the content of
given file location and output pointer is used for writing
to a given file location.
Each time an input and output operation takes place,
the appropriate pointer is automatically advanced.
By Hansa Halai
24. Default action:
When we open file in read only mode the input pointer
automatically set at the beginning so that we can read the
file from start.
When we open file in write only mode the input pointer
the existing contents are deleted and the output pointer is
set at the beginning. This enables us to write the file from
start.
By Hansa Halai
25. By Hansa Halai
In case we want to open an existing file to add more
data, the file is opened in “append” mode, which is move
file pointer at the end of file.
26. Functions for manipulation of file pointer:
As we shown file pointer takes place automatically by
default. But how do we move a file pointer to any other
desired location. This is possible only if we can take
control of movement of file pointers ourselves.
The File stream classes support the following function
to manage such situation:
seekg(): Move get pointer to specific location.(read)
seekp():Move put pointer to specific location.(write)
tellg(): Gives the current position of the get pointer.
tellp():Gives the current position of the put pointer.
By Hansa Halai
27. Example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream dataFile("sentence.txt", ios::out);
char ch;
cout << "Type a sentence and be sure to end it with a ";
cout << "period.n";
while (1)
{
cin.get(ch);
dataFile.put(ch);
if (ch == '.')
break;
}
By Hansa Halai
29. Example-2:
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream outf("test");
cout<<"Enter String: ";
char str[20];
cin>>str;
outf<<str;
cout<<"n";
int p=outf.tellp();
cout<<"size of file:"<<p;
outf.close();
By Hansa Halai
Represent the number of bytes in the file
31. Specifying the offset:
We have just seen how to move a file pointer to a desired
location using the seek function. The argument to these functions
represents the absolute position in the file.
Seekg() and seekp() can also be used with two arguments as
follows:
seekg(offset,refposition);
seekp(offset,refposition);
By Hansa Halai
32. The parameter offset represent the number of bytes the
file pointer is to be moved from the location specified by
the parameter refposition.
The refposition takes one of the following three
constants defined in the ios class:
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
Ex: (In File pointer and their Manipulations Ex-1)
By Hansa Halai
33. SEQUENTIAL INPUT AND OUTPUT OPERATIONS:
The file stream classes support a number of
member functions for performing the input and
output operation on file.
One pair of the function get() and put() are
designed for handling a single character at a time.
Another pair of functions write() and read() are
designed to write and read block of binary data.
By Hansa Halai
34. put() and get() function:
• The function put() writes a single character to associated
stream.
• The function get() reads a single character from associated
stream .
• Ex:
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char str[100];
cout<<"Enter String: ";
cin>>str;
By Hansa Halai
35. int len=strlen(str);
fstream file;
cout<<"nOpen file and store string in it..";
file.open("TEXT",ios::in | ios::out);
for(int i=0;i<len;i++)
{
file.put(str[i]);
}
file.seekg(0);
char ch;
cout<<"nReading the file content..";
while(file){
file.get(ch);
cout<<ch<<"n";
}
return 0;
}
By Hansa Halai
36. write() and read() functions:
• The function write() and read() handle data in binary form.
• This means that the values are stored in the disk file in
the same format in which they are stored in the internal
memory.
• The binary format is more accurate for storing the
numbers as they are stored in the exact internal
representation.
• The binary input and output function takes the following
form.
infile.read((char *) & V, sizeof(V));
outfile.write((char *) & V, sizeof(V));
By Hansa Halai
file class
object
Variable name
37. These functions takes two arguments, the first is the address of
variable V and the second is the length of that variable in byte.
The address of the variable must be cast to type char*.
Ex:
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
const char* filename="BINARY";
int main()
{
char C[4]={'A','B','Z','*'};
ofstream outfile;
outfile.open(filename):
By Hansa Halai