A presentation
on
Working With Files
Presented by:
Kamal Barali
Prabhat Kiran Sigdel
Raju Bhattarai
Yubraj Khadka
Introduction
A file is a collection of related data stored in a particular area on
the disk. Programs can be designed to perform the read and
write operation on these files.
A program involves either or both of the following kind of data
communication.
1. Data transfer between console unit and the program.
2. Data transfer between the program and a disk file .
To handle the file i/o operation which are similar to
console I/O operation.
The input stream extracts (reads) data from file & output
stream inserts (write) data to the file.
The input stream and link it with a program and input file.
The output operation involves the creation of an input
stream with a program and input file.
The output operation involves the creating & output
stream with the necessary link with program & output file.
Classes for file stream operations
CLASSES FOR FILE STREAM OPERATIONS
Class Contents
filebuf Its purpose is to set the filke buffers to read and write .
Contains openprot constant used in the open() of file streasm
classes. Also contains close() and open() as members .
fstreambase Provides operation common to the file stream serve as a base
for fstream ,ifsteream and ofstream class .contains open() and
close() functions
ifstream This data type represents the input file stream and is used to
read information from files.
ofstream This data type represents the output file stream and is used to
create files and to write information to files.
fstream This data type represents the file stream generally, and has
the capabilities of both ofstream and ifstream which means it
can create files, write information to files, and read information
from files.
OPENING & CLOOSING A FILE
A file must be opened before you can read from it or write to it. Either ofstream or
fstream object may be used to open a file for writing. And ifstream object is used
to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the
file should be opened.
Mode flag Description
ios::in Open file in reading mode
ios::out Open file in writing mode
ios::app Append mode. All output to that file to be
appended to the end
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
The filename is a string character that make up a valid
filkename for the operation system.it may contain two parts ,a
primary name and an optional period with extension.
Example
input.data
Salery
A file can be opened in two ways
1. Using the constructor function of class
2. Using the member function open of the respective classes
3. Using constructor function
The class ofstream is used to create the output stream
ifstream to create the input stream.
syntax
ifstream stream_object(“file_name”,mode);
ofstream stream_object(“file name”,mode);
Example
#include<iostream>
#include<fstream.h>
int main()
{
ofstream outf("ITEM"); //connect ITEM FIle to outf
cout<<"Enter item name:";
char name[30];
cin>>name; //get name from keyboard and
outf<<name<<"\n"; //Write To file ITEM
cout<<"Enter item cost:";
float cost;
cin>>cost; //get cost from key boards and
outf<<cost<<"\n"; //Write to file item
outf.close(); //Disconnect ITEM file from outf
ifstream inf("ITEM"); // Connect ITEMS file to inf
inf>>name; //Read name from file
inf>>cost; //Read cost from file
cout<<"\n";
cout<<"Item name:"<<name<<"\n";
cout<<"Item cost:"<<cost<<"\n";
inf.close(); //Disconnect ITEM from inf
return 0;
output
Enter item name:DVD
Enter item cost :20
Item name:DVD
Item price:20
OPEN FILE USING OPENFUNCTION
Open file can be used to open multiple files that uses
the same string object
Syntax:
stream-_class stream_object;
stream_object.open(“filename”);
Eg:
ofstream fout;
fout.open(“kcc.txt”);
DETECTING END OF FILE
Detection of the end of file condition is necessary for
preventing any further attempt to read data from the file .
a) Using stream oobject
An ifstream object such as fin returns a value of 0 if any error
occurs in the file operation including the end of file condition.
Eg:
ifstream fin;
fin.open(“abc”);
while(fin)
{
……
}
a) Using member function EOF()
Eof is amember function of ios class it
returns a non zero value if eof condition
is encounter otherwise zero
Eg:
Ifstream fin;
Fin(“abc”);
While(fin.eof()=0)
{
..
}
MORE ABOUT OPEN(): FILE MODES
The general form of the function open() with two arguments i.e
File name & file mode.
Stream_object.open(“filename”,mode);
The second arguments mode specifies the purpose for which
the files is opened .
The prototype of these member function contains default
values for the second arguments and therefore they use fthe
default values in the absence of actual values.default values
are
Ios::in (for reading only) (ifstream function)
ios::out (for writing only) (ofstream function)
File mode parameters
Parameter Meaning
ios::in Open file for reading only
ios::out Open file for writing only
ios::app Open file for append
ios::binary Binary file
ios::nocreate Open fails if the file doesnot exist
Ios::noreplace Open fails if the file already exists
ios::trunc Delate the contents of file if it exists
File pointer :
Each file has two associated pointer known as the file
pointer .one is called inputr pointer (get pointer) and
another is called output pointer(put pointer )
Input pointer (get) points beginning of the file
Output pointer (put) points beginning of the file
Append points end of the file .
#include<iostream>
#include<fstream.h>
#include<string.h>
int main()
{
char string[80];
cout<<"Enter a string:";
cin>>string;
int len=strlen(string);
fstream file; //input and output stream
cout<<"\nopening the 'text' file and storing the string in it.\n\n";
file.open("text",ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(string[i]); //put character to file
file.seekg(0); //go to start
char ch;
cout<<"Reading the file contents:";
while(file)
{
file.get(ch); //get the character from file
cout<<ch; //display it on screen
}
return o;
}
output
Enter a string:Working_with_file
Opening the 'text' file and storing the string in it.
Reading the file contents: Working_with_file
Manipulation of file pointer
File stream supports the following function to manage
the movement of the file pointer
1. Seekg() :This function moves the get pointer
(input pointer) to specifid location.
2. Seekp(): This function moves the output (put) pointer
to the specified location.
3. Tellg(): Gives the current position of the get pointer
4. Tellp(): gives the current position of put pointer
Syntax
input_file_object.seekg(offset,refposition);
input_file_object.seekp(offset,refposition);
integer_variable=input_file_object.tellg();
integer_variable=input_file_object.tellp();
Example:
ofstream out;
Out.open(“abc”,ios::app);
Int x;
x=out.tellp();
Offset() : The parameter offset represents the
number of bytes the file pointer need to be moved
from the location specified by the ref position.
Refrance position can take one of the following
ios::beg (beginning of the file )
ios::cur (current position of pointer )
ios::end (end of file)
Example
fin.seekg(0,ios::end); = goto beginning of file
fin.seekg(-100,ios::end);
(+ve =moves forward)
(-ve =move backward)
SEQUENTIAL INPUT AND OUTPUT OPERATIONS
File stream classes support a number of member function
for performing the input and output operations on file .on pair
of function ,put() and get() are designed for handling a single
character at a time .Another pair of function write() and read()
are designed to write a read block of binary data.
Put() and get() functions
the function put() writes a single character to the associated
stream similarly the function get() reads the single character
from the associated stream.
write() and read() Functions
the function write() and read() unlike the function put() and
get() handles the data in binary form this means that the
values are stored in disk file in the same format in way they
are stored in the internal memory
Syntax :
infile.read((char*)&v,size of(v));
Outfile.write((char*)&v,sizeof(v));
Reading and Writing a Class Objects
The function read and write designed to do
exactly reading and writing the objects in the dis
k. The function handles the entire structure of an
objects as a single unit.
#include<iostream>
#include<conio.h> }
#include<fstream.h> };
using namespace std; int main()
class student {
{ student std;
char name[30]; fstream file;
int id; file.open("student .txt",ios::in|ios::out);
public: cout<<"Enter student details\n";
void getdata() for(int i=0;i<10;i+)
{ {
std.getdata();
cout<<"Enter a name\n"; file.write((*char)&std,sizeof(std));
cin>>name; std.display();
cout<<"Enter ID\n";
cin>>id; }
file.close();
} getch();
void display() return 0;
{ }
cout<<"Name"<<name<<endl;
cout<<"I D"<<id<<endl;
Thank You