KEMBAR78
File Handling | PDF | Computer File | Filename
0% found this document useful (0 votes)
6 views10 pages

File Handling

The document provides an introduction to file handling in C++, detailing the essential operations such as opening, reading, writing, and closing files. It explains various methods for input and output, including using stream classes, and demonstrates reading and writing data using both text and binary formats. Additionally, it covers random access file access techniques, including the use of seek functions and stream positions.

Uploaded by

Prashun Dhungana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

File Handling

The document provides an introduction to file handling in C++, detailing the essential operations such as opening, reading, writing, and closing files. It explains various methods for input and output, including using stream classes, and demonstrates reading and writing data using both text and binary formats. Additionally, it covers random access file access techniques, including the use of seek functions and stream positions.

Uploaded by

Prashun Dhungana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling:

Input/output with Files


INTRODUCTION

All programs require some input and produce some output but those input and output are lost as the
program terminates. Files are required to save our data for future use. Programs would not be very
useful if they cannot store data in files. When data volume is large it is generally not convenient to enter
the data through console. In case cases data can be stored in a file and then the program can read the
data from data file rather than from the console.

The various operations possible on a data file using C++ programs are:

1. Opening a file
2. Reading data stored in the file
3. Writing/appending data from a program into a data file
4. Saving the data file onto some secondary storage device
5. Closing the data file once the ensuring operations are over
6. Checking status of file operation

Stream Class Hierarchy

Opening a file

The first operation generally done on an object of one of the stream classes is to associate it to a real
file, that is to say, to open a file. The open file is represented within the program by a stream object and
any input or output performed on this stream object will be applied to the physical file. A data file can
be opened in a program in many ways. These methods are described below:

Ifstream filename(“filename<with path>”);

OR

ofstream filename(“filename<with path>”);

Closing a file

When reading, writing or consulting operations on a file are complete we must close it to so that it
becomes available again. In order to do that we shall call the member function close (), that is in charge
of flushing the buffers and closing the file. Its form is quite simple:

Compiled By: Sushant Paudel


void close()

Once this member function is called, the stream object can be used to open another fil;e and the file is
available again to be opened by other processes.

Unformatted Input/output

Reading Data by getLine () Method:

With extraction operator reading terminates after reading white space character therefore above
program is able to read single word from file. We can overcome above problem by using getline ()
function as below:

#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char str[80];
fin.open("E:\\file\\abc.txt");
fin.getline(str,79);
cout<<"From file:"<<str<<endl;
getch();
return 0;
}
Output:
From file: This is my first program in file handling

Using get and put Methods and Detecting End of File

The class ifstream has a member function eof() that returns a nonzero value if the end of file has been
reached. This value indicates that there are no more characters in the file to be read further. This
function is therefore used in the while loop for stopping condition. End of file can be detected in two
ways: Using EOF () member function and using filestream object.

Detecting End of File using EOF() member function

#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
int main()

Compiled By: Sushant Paudel


{
ifstream fin;
char ch;
fin.open("E:\\file\\abc.txt");
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
getch();
return 0;
}
Output:
This is my first program in file handling
Hello again
Detecting End of File using Filestream Object
#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char ch;
fin.open("E:\\file\\abc.txt");
while(fin))
{
fin.get(ch);
cout<<ch;
}
getch();
return 0;
}
Output:
This is my first program in file handling
Hello again

Write a program to read the contents of a file and display them on the screen insertion opereator and
getline method:
#include<conio.h>
#include<iostream>
#include<fstream>

Compiled By: Sushant Paudel


using namespace std;
int main()
{
ifstream fin;
char str[100];
fin.open("E:\\file\\abc.txt");
while(!fin.eof())
{
fin.getline(str,79);
cout<<str;
}
getch();
return 0;
}
Output:

This is my first program in file handling


Hello again
Write a program to read the contents of a text file and display them on the screen using extraction
operator

#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char str[100];
fin.open("E:\\file\\abc.txt");
while(!fin.eof())
{
fin>>str;
cout<<str<<" ";
}
getch();
return 0;
}
Output:
This is my first program in file handling
Hello again
Reading and Writing by Using Read() and Write Member Functions

Compiled By: Sushant Paudel


Files streams include two members functions specifically designed to input and output binary data
sequentially: write and read. The first one (write) is a member function of ostream class inherited by
ofstream and read is a member function of isstream class that is inherited by ifstream. Objects of class
fstream have both members. Their prototypes are:
Syntax for write()
FileObject.write ((char*)&object,sizeof(object))
Syntax for read()
FileObject.read ((char*)&object,sizeof(object))

Example:
Program to write data by using write() member function

#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
public:
int roll;
char name[20];
char address[20];
};
int main()
{
Student s;
ofstream fout;
fout.open("student.dat");
cout<<"Enter Rollno:"<<endl;
cin>>s.roll;
cout<<"Enter Name:"<<endl;
cin>>s.name;
cout<<"Enter Address:"<<endl;
cin>>s.address;
fout.write((char *)&s,sizeof(Student));
fout.close();
cout<<"Writing complete"<<endl;
getch();
return 0;

Compiled By: Sushant Paudel


}

Output:
Enter Rollno:
1
Enter Name:
Kamal
Enter Address:
Kathmandu
Writing Complete

Program to read data from a binary File using read() member function
#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
public:
int roll;
char name[20];
char address[20];
};
int main()
{
Student s;
ifstream fin;
fin.open("student.dat");
fin.read((char *)&s,sizeof(Student));
cout<<"Rollno:"<<s.roll<<endl;
cout<<"Name:"<<s.name<<endl;
cout<<"Address:"<<s.address<<endl;
fin.close();
cout<<"Reading complete"<<endl;
getch();
return 0;
}
Writing multiple objects to file
#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;

Compiled By: Sushant Paudel


class Student
{
private:
int roll;
char name[20];
char address[20];
public:
void read_data()
{
cout<<"Enter Rollno:"<<endl;
cin>>roll;
cout<<"Enter Name:"<<endl;
cin>>name;
cout<<"Enter Address:"<<endl;
cin>>address;
}
void write_data()
{

};
int main()
{
Student s;
ofstream fout;
fout.open("student.dat");
for(int i=1;i<=5;i++)
{
cout<<"Enter rollno, name and address of "<<i<<"th student"<<endl;
s.read_data();
fout.write((char *)&s,sizeof(Student));
}
fout.close();
cout<<"Writting complete"<<endl;
getch();
return 0;
}
Reading multiple objects from file

#include<conio.h>
#include<iostream>

Compiled By: Sushant Paudel


#include<fstream>
using namespace std;
class Student
{
private:
int roll;
char name[20];
char address[20];
public:
void write_data()
{
cout<<roll<<"\t"<<name<<"\t"<<address<<endl;
}

};
int main()
{
Student s;
ifstream fin;
fin.open ("student.dat");
cout<<"Rollno\tName\tAddress"<<endl;
for(int i=1;i<=5;i++)
{
fin.read ((char *)&s,sizeof(Student));
s.write_data();
}
fin.close();
cout<<"Reading complete"<<endl;
getch();
return 0;
}
Random Access File Access

In some situations, you might want to read some record randomly not sequentially. You can do this
using two models: One uses an absolute location in the stream called the streampos; the second woks
like the standard C library functions fseek () for a file and moves a given number of bytes from the
beginning, current and end part of file.

The streampos approach requires that you first call a “tell” function; tell() for an ostream or
tellg() for an istream. (The “p” refers to the “put pointer” and “g” refers to the “get pointer”). This
function returns a streampos which you can later use in calls to seekp () for an ostream or seekg () for an

Compiled By: Sushant Paudel


stream. The second approach is a relative seek and uses overloaded versions of seekp() and seekg(). The
first argument is the number of characters to move, it can be positive or negative.
The second argument is the seek direction. Some important member functions are:
seekg(): It is used to move reading pointer forward and backward.
Syntax:
Fileobject.seekg (50,ios::cur);// Moves 50 bytes forward from current
Fileobject.seekg (50,ios::beg);// Moves 50 bytes forward from beginning

Fileobject.seekg (50,ios::end);// Moves 50 bytes forward from end

seekp ():-It is used to move writing pointer forward and backward


Syntax:
Fileobject.seekp (no_of_bytes, mode)
fout.seekp (50,ios::cur)// Moves 50 byes forward from current position
fout.seepk (50, ios::beg) // Moves 50 bytes forward from current position
fout.seekp (50,ios::end);// Moves 50 bytes forward from end

tellp():- It returns the distance of writing pointer from the beginning in byes
Syntax:
FileObject.tellp ()
Example:
long n = fin.tellp ();
tellg():- It returns the distance of reading pointer from the beginning in bytes.
Syntax:
FileObject.tellg ()
Example:
Long n = fout.tellg ();

Example:
Program to read third object from the file student.dat
#include<conio.h>
#include<iostream>
#include<fstream>
using namespace std;
class student
{
int roll;
char name[20];
char address[20];
public:
void display()

Compiled By: Sushant Paudel


{
cout<<"Rollno:"<<roll<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Address:"<<address<<endl;
}

};
int main()
{
student s;
int i;
ifstream fin;
fin.open("stdudent.dat");
fin.seekg(sizeof(s)*2,ios::cur);
fin.read((char*)&s,sizeof(student));
s.display();
fin.close();
getch();
return 0;
}
Output:
Rollno:3
Name: Kamal
Address: Kathmandu

Compiled By: Sushant Paudel

You might also like