8/7/2019 cap 202 shivangi
1/24
HOME WORK-3
Submitted by:- Submitted to:-
Name Shivangi shukla Miss. Tajinder Kaur
BCA 1st year
Roll-no:- A17
Q1. Differentiate class to basic and basic to
class type conversions with example.
8/7/2019 cap 202 shivangi
2/24
Ans:-
Conversion from a basic type to a class type may be
achieved using SUITABLE CONSTRUCTORS IN CLASS.
EX:
class distance
{
int feet;
float inch;
public:
distance(float p) //costructor to concert basic type to
class type
{
feet= (int) p;
inch=(p-feet)*12;
}
void show()
{
cout
8/7/2019 cap 202 shivangi
3/24
}
};
//Conversion CLASS TO BASIC//String object to basic string
#include
#include
#include
classstring
{
char *p;
int len;
public:
string()
{}
string(char *a)
{
len=strlen(a);
p=newchar[len+1];
strcpy(p,a);
}
operatorchar*()
8/7/2019 cap 202 shivangi
4/24
{
return(p);
}
void display()
{
cout
8/7/2019 cap 202 shivangi
5/24
Q2. Explain the various methods to open a file. Also
write a program to create a file and then display
its contents on the screen with the help of open()
function.
Ans:---There are some classes provided to us forperforming many other operations other thanopening:-----------------------------------------------------------
Classes for the file stream operations :The I/O system of C++ contains a set of classes that define thefile handling methods.
These include ifstream, ofstream and fstream.
These classes, designed to manage the disk files, are declared infstream.h and therefore we must include this file in any programthat uses files.
8/7/2019 cap 202 shivangi
6/24
Details of some useful classes :filebufIts purpose is to set the file buffer to read and write. Containsopenprot constant used in the open() of the filestream classes.Also contains close() and open() as member functions.
fstreambaseProvides operations common to the file streams. Serves as a basefor fstream, ifstream and ofstream classes. Contains open() andclose() functions.
ifstreamProvides input operations. Contains open() with default inputmode. Inherits the functions get(), getline(), read(), seekg() andtellg() functions from istream.
ofstreamProvides output operations. Contains open() with default outputmode. Inherits put(), seekp(), tellp(), and write() functions fromostream.
http://s726.photobucket.com/albums/ww266/puneetnick007/?action=view¤t=qq-1.jpg8/7/2019 cap 202 shivangi
7/24
fstreamProvides support for simultaneous input and output operations.Contains open() with default input mode. Inherits all the functionsfrom istream and ostream classes through iostream.
The ifstream, ofstream and fstream classes are declaredin the file fstream.hThe istream and ostream classes are also included in thefstream.h file.
there are various methods for opening a file:--------------------------
Opening and closing a file :For opening a file, we must first create a file stream and than linkit to the filename.
A filestream can be defined using the classes ifstream, ofstream,and fstream that are contained in the header file fstream.h
A file can be opened in two ways:Using the constructor function of the class. This method is
useful when we open only one file in the stream.
Using the member function open() of the class. Thismethod is used when we want to manage multiple filesusing one stream.
Using ConstructorCreate a file stream object to manage the stream using theappropriate class. That is, the class ofstream is used to create the
output stream and the class ifstream to create the input stream.
Initialize the file object with the desired filename, e.g.:
ofstream outfile(sample.txt);
8/7/2019 cap 202 shivangi
8/24
The above statement creates an object outfile of class ofstreamthat manages the output stream. This statement also opens thefile sample.txt and attaches it to the output stream for writing.
Similarly, the statement declared in as an ifstream object andattaches to the file sample.txt for reading.
ifstream infile(sample.txt);
Program: Writing and reading data into file, using constructors
# include
void main(){ofstream outfile(sample.txt); // create file for outputchar ch = a;int i = 12;float f = 4356.15;char arr[ ] = hello;outfile > arr; // read data from file
cout
8/7/2019 cap 202 shivangi
9/24
{
char str[]=C++ is superset of C. It is an object-oriented /
programming language.;
ofstream outfile(sample2.txt); // Open the file in write mode
for(int i = 0; i < strlen(str); i++)
outfile.put(str[i]); // write data into the file, character by
character.
}
Writing and reading Objects of a class :So far we have done I/O of basic data types. Since the class
objects are the central elements of C++ programming, it is quite
natural that the language supports features for writing and
reading from the disk files objects directly.
The binary input and output functions read() and write() aredesigned to do exactly this job.
The write() function is used to write the object of a class into the
specified file and read() function is used to read the object of the
class from the file.
Both these functions take two arguments:
1. address of object to be written.
2. size of the object.
The address of the object must be cast to the type pointer to
char.
One important point to remember is that only data members are
written to the disk file and the member functions are not.
8/7/2019 cap 202 shivangi
10/24
Writing an object into the file
#includeclass Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout > name;cout > age;
}
} ; // End of the class definition
void main()
{
Person per ; // Define an object of Person class
per.getData(); // Enter the values to the data members of theclass.
ofstream outfile(Person.txt); // Open the file in output mode
outfile.write((char*)&per, sizeof(per)); // Write the object into the
file
}
fstream object can be used for both input & output.
In the open() function we include several mode bits to specify
certain aspects of the file object.
8/7/2019 cap 202 shivangi
11/24
app -> To preserve whatever was in the file before. Whatever we
write to the file will be appended to the existing contents.
We use in and out because we want to perform both input and
output on the file.
eof() is a member function of ios class. It returns a nonzero value
if EOF is encountered and a zero otherwise.
Parameters of open() function
Parameter Meaning
ios::app Append to end of the fileios::ate Go to end of the file on opening
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exists
ios::out Open file for writing only
ios::trunc Delete contents of the file if it exists
opening a file using the openfunction:--------------------------------EX:- #include
#include
#include
using namespace std;
int main()
{
fstream File;
8/7/2019 cap 202 shivangi
12/24
string array[10];
File.open("Data.txt", ios::out);
if (File.is_open ()) {
for (int x = 0; x
8/7/2019 cap 202 shivangi
13/24
goes to the end of the file and adds the new data to it.
ios::ate If FileName is a new file, data is written to it and
subsequently
added to the end of the file.
If FileName already exists and contains data, then it is openedand data is
written in the current position.
ios::in If FileName is a new file, then it gets created fine as anempty file.
If FileName already exists, then it is opened and its content ismade
available for processing
ios::out If FileName is a new file, then it gets created fine as anempty file.
Once/Since it gets created empty, you can write data to it.
If FileName already exists, then it is opened, its content is
destroyed, and
the file becomes as new. Therefore you can create new data towrite to it.
Then, if you save the file, which is the main purpose of this mode,the new
8/7/2019 cap 202 shivangi
14/24
content is saved it.*This operation is typically used when youwant to save
a file
ios::trunc If FileName already exists, its content is destroyed andthe file
becomes as new
ios::nocreate If FileName is a new file, the operation fails becauseit
cannot create a new file.
If FileName already exists, then it is opened and its content ismade
available for processing
ios::noreplace If FileName is a new file, then it gets created fine.
If FileName already exists and you try to open it, this operationwould fail
because it cannot create a file of the same name in the same
location.
8/7/2019 cap 202 shivangi
15/24
Q4. Jot down the various functions for manipulation of filepointers.
Ans:- Functions for manipulation of file pointers
seekg
Sets the position of the get pointer. The get pointer determinesthe next location to be
read in the source associated to the stream.
Syntax:
seekg ( position );
Using this function the stream pointer is changed to the absolute
position (counting
from the beginning of the file). seekg ( offset, direction );
Using this function, the position of the get pointer is set to anoffset value relative to
some specific point determined by the parameter direction. offsetis of the member
type off_type, which is also an integer type. And direction is oftype seekdir, which is an
enumerated type (enum) that determines the point from whereoffset is counted from.
8/7/2019 cap 202 shivangi
16/24
seekp
The seekp method changes the location of a stream object's filepointer for output (put
or write.) In most cases, seekp also changes the location of astream object's file pointer
for input (get or read.)
seekp ( position );
Using this function the stream pointer is changed to the absoluteposition (counting
from the beginning of the file).
seekp ( offset, direction );
Using this function, the position of the put pointer is set to anoffset value relative to
some specific point determined by the parameter direction. offsetis of the member
type off_type, which is also an integer type. And direction is oftype seekdir, which is an
enumerated type (enum) that determines the point from whereoffset is counted from
tellg
The tellg() function is used with input streams, and returns thecurrent "get" position of
the pointer in the stream.
Syntax:
pos_type tellg();
8/7/2019 cap 202 shivangi
17/24
It has no parameters and return a value of the member typepos_type, which is an
integer data type representing the current position of the getstream pointer.
tellp
Returns the absolute position of the put pointer. The put pointerdetermines the
location in the output sequence where the next output operationis going to take place.
Syntax:
pos_type tellp();
The tellp() function is used with output streams, and returns thecurrent "put" position
of the pointer in the stream. It has no parameters and return avalue of the member
type pos_type, which is an integer data type representing thecurrent position of the put
stream pointer.
Specifying the offset :
The seek functions seekg() and seekp() can also be used with twoarguments
as follows:
seekg(offset, refposition);
seekp(offset, refposition);
8/7/2019 cap 202 shivangi
18/24
The parameter offset represents the number of bytes the filepointer to be
moved from the location specified by the parameter refposition.
The refposition takes one of the following these constant definedin the ios
class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.
EX:
class person
{
private:
char name[40];
int age;
public:
void showData()
{
cout
8/7/2019 cap 202 shivangi
19/24
ifstream infile; // create input file
infile.open(Person.txt); // open the file
infile.seekg(0, ios::end); // go to end from 0 byte
int endposition = infile.tellg(); // find where we are
int n = endposition/sizeof(person); // number of persons
cout
8/7/2019 cap 202 shivangi
20/24
ios::bad Check if badbit is set (public member function)
ios::rdstate Get error state flags (public member function)
ios::clear Set error state flags (public member function)
Check if the state of the stream is good for i/o operations. (publicmember
#include
#include
#include
using namespace std;
void check_stream_state1(const fstream &s)
{
int state = s.rdstate();
if (!state)
{
cout
8/7/2019 cap 202 shivangi
21/24
cout
8/7/2019 cap 202 shivangi
22/24
if(s.fail())
cout
8/7/2019 cap 202 shivangi
23/24
//using member function eof()
while(!input.eof())
{
getline (input, text);
cout
8/7/2019 cap 202 shivangi
24/24
return 0; }