Unit Ii-Oops
Unit Ii-Oops
Pointers in c++:
A pointer is a variable whose value is the address of another variable. every variable is a memory
location and every memory location has its address defined which can be accessed using ampersand
(&) operator which denotes an address in memory.
(c) Finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand.
#include <iostream>
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
the object pointers are declared by placing in front of a object pointer's name. It
takes the following general form :
class-name ∗ object-pointer ;
In C++ programming, this is a keyword that refers to the current instance of the class.
There can be 3 main usage of this keyword in C++.
Let's see the example of this keyword in C++ that refers to the fields of current class.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
Virtual function
Virtual function is a member function that is declared within the base class and can be redefined by
the derived class.
Syntax:
An Example program:
1. #include <iostream>
2. using namespace std;
3. class base
4. {
5. public:
6. void show()
7. {
8. std::cout << "Base class" << std::endl;
9. }
10. };
11. class derived1 : public base
12. {
13. public:
14. void show()
15. {
16. std::cout << "Derived class 1" << std::endl;
17. }
18. };
19. class derived2 : public base
20. {
21. public:
22. void show()
23. {
24. std::cout << "Derived class 2" << std::endl;
25. }
26. };
27. int main()
28. {
29. base *b;
30. derived1 d1;
31. derived2 d2;
32. b=&d1;
33. b->show();
34. b=&d2;
35. b->show();
36. return 0;
37. }
In the above code, we have not used the virtual method. We have created a base class that contains
the show() function. The two classes are also created named as 'derived1' and 'derived2' that are
inheriting the properties of the base class. Both 'derived1' and 'derived2' classes have redefined the
show() function. Inside the main() method, pointer variable 'b' of class base is declared. The objects
of classes derived1 and derived2 are d1 and d2 respectively. Although the 'b' contains the addresses
of d1 and d2, but when calling the show() method; it always calls the show() method of the base class
rather than calling the functions of the derived1 and derived2 class.
To overcome the above problem, we need to make the method as virtual in the base class. Here,
virtual means that the method exists in appearance but not in reality. We can make the method as
virtual by simply adding the virtual keyword proceeding to the function. In the above program, we
need to add the virtual keyword that precedes to the show() function in the base class shown as
below:
Once the above changes are made, the output would be:
Important points:
o It is a run-time polymorphism.
o Both the base class and the derived class have the same function name, and the base class is
assigned with an address of the derived class object then also pointer will execute the base
class function.
o If the function is made virtual, then the compiler will determine which function is to execute
at the run time on the basis of the assigned address to the pointer of the base class.
A pure virtual function is a virtual function that has no definition within the class. Let's understand
the concept of pure virtual function through an example.
In the above pictorial representation, shape is the base class while rectangle, square and circle are the
derived class. Since we are not providing any definition to the virtual function, so it will
automatically be converted into a pure virtual function.
o A pure virtual function is a "do nothing" function. Here "do nothing" means that it just
provides the template, and derived class implements the function.
o It can be considered as an empty function means that the pure virtual function does not have
any definition relative to the base class.
o Programmers need to redefine the pure virtual function in the derived class as it has no
definition in the base class.
o A class having pure virtual function cannot be used to create direct objects of its own. It
means that the class is containing any pure virtual function then we cannot create the object
of that class. This type of class is known as an abstract class.
A virtual function is a member function in a base A pure virtual function is a member function in a base
class that can be redefined in a derived class. class whose declaration is provided in a base class and
implemented in a derived class.
The classes which are containing virtual functions are The classes which are containing pure virtual function
not abstract classes. are the abstract classes.
In case of a virtual function, definition of a function is In case of a pure virtual function, definition of a
provided in the base class. function is not provided in the base class.
The base class that contains a virtual function can be The base class that contains a pure virtual function
instantiated. becomes an abstract class, and that cannot be
instantiated.
If the derived class will not redefine the virtual If the derived class does not define the pure virtual
function of the base class, then there will be no effect function; it will not throw any error but the derived
on the compilation. class becomes an abstract class.
All the derived classes may or may not redefine the All the derived classes must define the pure virtual
virtual function. function.
Concept of stream:
A C++ stream is a flow of data into or out of a program, such as the data written to cout or
read from cin.
For this class we are currently interested in four different classes:
o istream is a general purpose input stream. cin is an example of an istream.
o ostream is a general purpose output stream. cout and cerr are both examples of
ostreams.
o ifstream is an input file stream. It is a special kind of an istream that reads in data
from a data file.
o ofstream is an output file stream. It is a special kind of ostream that writes data out to
a data file.
The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<)
to display the output on a console
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of array is: " << ary << endl;
}
Output:
The cin is a predefined object of istream class. It is connected with the standard input device, which
is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the
input from a console.
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
22In C++ stream refers to the stream of characters that are transferred between the
program thread and i/o.
Stream classes in C++ are used to input and output operations on files and io devices.
These classes have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
Let's see the hierarchy and learn about them,
Now, let’s learn about the classes of the iostream library.
ios class − This class is the base class for all stream classes. The streams can be input or
output streams. This class defines members that are independent of how the templates of
the class are defined.
istream Class − The istream class handles the input stream in c++ programming language.
These input stream objects are used to read and interpret the input as a sequence of
characters. The cin handles the input.
ostream class − The ostream class handles the output stream in c++ programming
language. These output stream objects are used to write data as a sequence of characters
on the screen. cout and puts handle the out streams in c++ programming language.
Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream. To access manipulators, the file iomanip.h should be included in the
program. In this article, we have shared the list of Manipulators in C++ and functions of
manipulators with examples.
They are of two types one taking arguments and the other without argument.
C++ Manipulators
Manipulators are operators used in C++ for formatting output. The data is manipulated by the
programmer’s choice of display.
In this C++ tutorial, you will learn what a manipulator
is, endl manipulator, setw manipulator, setfill manipulator and setprecision manipulator are all explained
along with syntax and examples.
endl Manipulator:
This manipulator has the same functionality as the ‘n’ newline character.
For example:
1. cout << "Exforsys" << endl;
2. cout << "Training";
setw Manipulator:
Syntax:
setw(x)
Here setw causes the number or string that follows it to be printed within a field of x characters wide and
x is the argument set in setw manipulator.
The header file that must be included while using setw manipulator is .
Example:
#include <iostream>
#include <iomanip>
void main( )
{
int x1=123,x2= 234, x3=789;
cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl
<< setw(8) << "test123" << setw(20)<< x1 << endl
<< setw(8) << "exam234" << setw(20)<< x2 << endl
<< setw(8) << "result789" << setw(20)<< x3 << endl;
}
Output:
test 123
exam 234
result 789
setfill Manipulator:
This is used after setw manipulator.
If a value does not entirely fill a field, then the character specified in the setfill argument of the
manipulator is used for filling the fields.
Example:
#include <iostream>
#include <iomanip>
void main()
{
cout << setw(15) << setfill('*') << 99 << 97 << endl;
}
Output:
********9997
setprecision Manipulator:
1. fixed
2. scientific
These two forms are used when the keywords fixed or scientific are appropriately used before the
setprecision manipulator.
The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation.
The keyword scientific, before the setprecision manipulator, prints the floating point number in scientific
notation.
Example:
#include <iostream>
#include <iomanip>
void main( )
{
float x = 0.1;
cout << fixed << setprecision(3) << x << endl;
cout << scientific << x << endl;
}
Output:
0.100
1.000e-001
The first cout statement contains fixed notation and the setprecision contains argument 3.
This means that three digits after the decimal point and in fixed notation will output the first cout
statement as 0.100. The second cout produces the output in scientific notation.
The default value is used since no setprecision value is provided.
10 getch();
return 0;
11
}
12
Output :
13
Enter hexadecimal = f
14
Hexadecimal = f
15
Octal value = 17
16 Decimal value = 15
17
In the above program, the variable i is inputted in hexadecimal form using hex manipulator
in cin statement. To display the number in different notations like hexadecimal, octal and
decimal, the manipulator’s hex, oct and dee are used.
The base of a number remains the same until changed explicitly. For example, suppose
the base of a number i of integer type is changed to hexadecimal (hex) during output. In
that case, it will display the output only in hexadecimal form until being specified explicitly
using dee or oct manipulators.
setbase(b) Manipulator
The setbase () manipulator is used to change the base of a numeric value during inputting
and outputting. It is an alternative to Dec, Oct and hex manipulators. It is a function that
takes a single integer argument(b) having values 8, 10 or 16 to set the base of the numeric
value to octal, decimal and hexadecimal, respectively. The default base is 10.
1
#include<iostream.h>
2
#include<iomanip.h>
3
int main() {
4
int num;
5
cout<<"Enter number in Octal form = ";
6 cin>>setbase(8)>>num;
10 return 0;
}
11
Output
12
Enter numberin Octal form = 21
13
Value of number in decimal fonn = 17
14
Value of number in octal fonn = 21
15
Value of number in hexadecimal fonn = 11
16
In the above program, the value of variable num is inputted in octal form using setbase(8)
manipulator in the cin statement. The value of the variable num is displayed in different
number systems by using setbase(b) manipulator with arguments values 10, 8 and 16.
setw(w) Manipulator
The setw() stands for set width. It is a function that takes a single integer argument which
specifies the amount of space used to display the required value. We typically use the
setw() manipulator for displaying output so that it becomes more understandable. It can be
used to format only one value at a time.
1
#include<iostream.h>
2
#include<iomanip.h>
3 #include<conio.h>
4 int main() {
getch();
8
return 0;
9
}
10
In the above program, the setw() manipulator causes the number or string that follows it in
the cout statement to be displayed within the specified width. The value to be displayed is
right-justified. The values of variable rollno and age are displayed within 8 spaces specified
using setw(S) manipulator. The value is padded with leading blank spaces as it doesn’t fill
the whole width.
If the value is larger than the specified width, it will not truncate the value, and the value is
printed as it is. For example
1 cout<<setw(2)<<"Roll is"<<setw(2)<<rollno;
the output is
setfill(c) Manipulator
The setfill() manipulator is used in conjunction with the setw() manipulator. The compiler
leaves the empty spaces on the left side of the required value if the set width is greater
than the needed space. If you wish to fill the blank space with an alternative character
instead of a blank space, you can use the
setfill () manipulator.
Generally, you will not want to change the fill character. However, one common example of
when you may want to is creating a program that prints cheques. To prevent the cheque
amount from being altered by the user, computer-generated cheque amounts are usually
printed with leading asterisks(*). This is done in C++ with a setfill() manipulator.
The setfill () manipulator takes a single character as an argument and fills the empty
spaces with the specified character c on the left of the value displayed if the width specified
using setw() manipulator is greater than the value to be displayed.
1
2 #inclucle<iostream.h>
3 #include<iomanip.h>
#include<conio.h>
4
int main() {
5 int age = 22,rollno = 910l; cout<<setfill('#');
6 cout<<setw(4)<<age<<setw(6)<<rollno<<endl;
7 cout<<setw(6)<<age<<setw(8)<<rollno;
8 getch();
return 0;
9 }
10 Output :
11 ##22##9101
12 ####22####9101
13
setprecision(n) Manipulator
The setprecision() manipulator is used to control the precision of floating-point numbers,
i.e. the number of digits to the right of the decimal point. By default, the precision of the
floating-point number displayed is 6. This precision can be modified by using a setprecision
() manipulator. This function takes an integer argument n that specifies the number of
digits displayed after the decimal point. The floating-point number will be rounded to the
specified precision.
1 #include<iostream.h>
2 #includi<iomanip.h>
3 #inelude<eonio.h>
int main() {
4 float a = 129.455396;
5 cout<<setprecision(2)<<a<<endl;
6 cout<<setprecision(3)<<a;
7 getch();
return 0;
8 }
9 Output :
10 129.46
11 129.455
12
13
In the above program, the setprecision (2) rounds the number a to 2 decimal places after
the decimal point, i.e. 129.46.
In C++ programming
we are using the iostream standard library, it provides cin and cout methods for reading from input and
writing to output respectively.
To read and write from a file we are using the standard C++ library called fstream. Let us see the
data types define in fstream library is:
fstream It is used to create files, write information to files, and read information from files.
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main () {
5. ofstream filestream("testout.txt");
6. if (filestream.is_open())
7. {
8. filestream << "Welcome to C++.\n";
9. filestream << "C++ Tutorial.\n";
10. filestream.close();
11. }
12. else cout <<"File opening is fail.";
13. return 0;
14. }
Output:
The I/O system of C++ contains a set of classes that define the file handling methods.
These include ifstream, ofstream and fstream. These classes are derived from fstreambase
and the corresponding iostream class in the figure: These classes are designed to manage
the disk files that are declared in fstream and therefore, we must include this file in any
program that uses files.
A file is a collection of related data stored in particular area on the disk.
The data transfer can take place in two ways,
1. Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.
File streams are used to transfer data between program and a disk file. Therefore a file stream
acts as an interface between the programs and the files. The file stream I/O operations are
similar to, consolestream I/O operations, The stream that provides the data to the program is
called as an input stream and the stream that is used to receive the data from the program is
called as an output stream. An input stream is used to extract the data from a file and an output
stream is used to insert the data to a file. Performing input operations on file streams requires
creation of an input stream and linking it with the program and the input file. Similarly performing
output operations on file streams requires establishment of an output stream with the necessary
links with the program and the output file.
The figure below shows the file stream hierarchy.
File management functions
the iostream standard library, which provides cin and cout methods for reading from
standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard
C++ library called fstream, which defines three new data types −
1
ofstream
This data type represents the output file stream and is used to create files and to
write information to files.
2
ifstream
This data type represents the input file stream and is used to read information
from files.
3
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.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening 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.
1
ios::app
Append mode. All output to that file to be appended to the end.
2
ios::ate
Open a file for output and move the read/write control to the end of the file.
3
ios::in
Open a file for reading.
4
ios::out
Open a file for writing.
5
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists,
following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the
screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input
and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to
read the line from outside and ignore() function to ignore the extra characters left by
previous read statement.
A stream is a name given to a flow of data at the lowest level. At the lowest level,
data is just the binary data without any notion of data type. Different streams are
used to represent the different kinds of data flow such as whether data is flowing
into the memory or out of the memory.
Each stream is associated with a particular class, that contains the member
functions and definitions for dealing with that particular kind of data flow. For
instance, the ifstream class represents the input disk files.
The stream that supplies data to the program is known as the input stream. It
reads the data from the file and hands it over to the program. The stream that
receives data from the program is known as output stream. It writes the received
data to the file.
The file I/O system of C++ contains a set of classes that define the file handling
methods. These classes, designed to manage the disk files, are declared in the
header file named fstream.h. Therefore, we must include this file in a program
that works with files. The classes defined inside the header file, fstream.h, derive
from the classes under the header file iostream.h, the header file that manages
console I/O operations.
Therefore, if you include the header file fstream.h in your file handling programs,
you need not to include iostream.h header file as classes of fstream.h inherit from
iostream.h only.
The function of these classes have been summarized in the following table :
Class Functions
filebuf It sets the file buffers to read and write. It contains close() and open() member functions to it
This is the base class for fstream, ifstream and ofstream classes. Therefore, it provides operations common
fstreambase
streams. It also contains the functions open() and close()
Being an input file stream class, it provides the input operations for file. It inherits the functions get(), getli
ifstream and functions supporting random access ( seekg() and tellg() ) from istream class defined inside the header
iostream.h
Being an output file stream class, it provides the output operations. It inherits the functions put() and write
ofstream
functions supporting random access ( seekp() and tellp() ) from ostream class defined inside the header file
It is an input-output file stream class. It provides support for the simultaneous input and output operations
fstream
all the functions from istream and ostream classes through the iostream class defined inside the header fil
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
char inform[80];
char fname[20];
char ch;
clrscr();
if(!fout)
{
cout<<"Error in creating the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}
cin.get(ch);
More Examples
fstreambase: It provides operations common to the file streams. It serves as a base for fstream,
ifstream and ofstream class. It also contain open() and close() functions.
ifstream: It provides input operations. It contains open() with default input mode. Inherits the
functions get(), getline(), read(), seekg() and tellg() functions from istrem
ofstream: It provides output operations. It contains open() with default output mode. Inherits put(),
seekp(), tellp() and write() functions from ostream.
fstream: It provides support for simultaneous input and output operations. inherits all the functions
from istream and ostream classes through iostream.
File streams are used to transfer data between program and a disk file. Therefore a file stream
acts as an interface between the programs and the files. The file stream I/O operations are
similar to, consolestream I/O operations, The stream that provides the data to the program is
called as an input stream and the stream that is used to receive the data from the program is
called as an output stream. An input stream is used to extract the data from a file and an output
stream is used to insert the data to a file. Performing input operations on file streams requires
creation of an input stream and linking it with the program and the input file. Similarly performing
output operations on file streams requires establishment of an output stream with the necessary
links with the program and the output file.
C++ contains several classes that are used to perform file I/O operations. These are ifstream,
ofstream and fstream classes which are derived from fstream base class and iostream class.
The file stream classes are declared in the header file “fstream.h”.
1. ifstream Class
This class supports input operations on the files. It inherits the functions get( ), getline( ), read(
), seekg( ) and tellg( ) from istream class. When the file is opened in default mode, it contains
open( ) function.
(i) get()
This function is used to read a single character from the file. The get pointer specifies the
character which has to be read from the file. This function belongs to fstream class.
Also read :Explain in detail I/O streams along with an example program
(ii) getline()
This function reads a line of text which ends with a newline character. It cam be called using cin
object as follows,
Size is number of characters to be read getline() function reads the input until it encounters ‘\n’
or size ⎼1 characters are read. When ‘\n’ is read. it is not saved instead it is replaced by the null
character.
(iii) read()
This function reads a block of data of length specified by an argument ‘n’. This function reads
data sequentially. So when the EOF is reached before the whole block is read then the buffer
will contain the elements read until EOF.
General syntax,
(iv) seekg()
This function is used to shift the input pointer (i.e., get) to the given location. It belongs to
ifstream. It is a file manipulator.
Also read :Draw console stream class hierarchy and explain its members
(v) tellg()
This function is used to determine the current position of the input pointer. It, belongs to ifstream
class.
2. ofstream Class
This class supports output operations on the files. It inherits the functions put(), seekp(), tellp()
and write() from ostream class. When the file is opened in default mode, it also contains the
open() function.
(i) put();
This function is used to write a single character to the file. A stream object specifies to which file
the character should be written. The character will be located at the position specified by the put
pointer. This function belongs to fstream class.
(ii) . seekp()
This function is used to shift the output pointer (i.e., put) to the given location. It belongs to
ofstream class. It is also a file manipulator.
(iii) tellp()
This function is used to determine the current position of the output pointer. It belongs to
ofstream class.
(iv) write()
This function displays a line on the screen. It is called using cout object as follows,
cout.write(line, size)
If the size of string is greater than the line (i.e., text to be displayed) then write() function stop
displaying on encountering null character but displays beyond the bounds of line.
This is the base class for ifstream, ofstream and fstream classes. It provides the operations that
are common to the file streams. It contains open( ) and class( ) functions.
Also read :Differentiate between Machine level, Assembly and High level languages
This class is used to set the file buffers to read and write operations. it contains the functions
open() and close(). It also contains a constant named Openport which is used
(i) open()
This function is used to create new files as well as open existing files.
General Form
Where, ‘mode’ specifies the purpose of opening a file. This ‘mode’ argument is optional, if it is
not given, then the prototype of member functions of the classes ifstream and ostream uses the
default, values for this argument. The default value are,
and ios ∷ out for ofstream functions i.e., open.in write only mode.
(ii) close()
A file can be closed using member function close(). This function neither takes any parameter
nor returns any value.
Syntax
stream_name.close();
Here,
stream_name is the name of the stream to which file is linked.
Whether it is the programming world or not, files are vital as they store data. This article
discuss working of file handling in C++. Following pointers will be covered in the article,
Opening a File
Writing to a File
Reading from a File
Close a File
A stream is an abstraction that represents a device on which operations of input and output
are performed. A stream can be represented as a source or destination of characters of
indefinite length depending on its usage.
In C++ we have a set of file handling methods. These include ifstream, ofstream, and
fstream. These classes are derived from fstrembase and from the corresponding iostream
class. These classes, designed to manage the disk files, are declared in fstream and
therefore we must include fstream and therefore we must include this file in any program
that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied to create files for
writing information to files
ifstream: This Stream class signifies the input file stream and is applied for reading
information from files
fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstreambase and from the corresponding
iostream class and they are designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:
Opening a File
Generally, the first operation performed on an object of one of these classes is to associate
it to a real file. This procedure is known to open a file.
1 open() function
Syntax
Here, the first argument of the open function defines the name and format of the file with the
address of the file.
The second argument represents the mode in which the file has to be opened. The
following modes are used as per the requirements.
Modes Description
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a class
so we need to create an object of this class to use its member functions. So we create
new_file object and call open() function. Here we use out mode that allows us to open the
file to write in it.
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
Example
ofstream new_file;
Here, input mode and append mode are combined which represents the file is opened for
writing and appending the outputs at the end.
As soon as the program terminates, the memory is erased and frees up the memory
allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of the file.
Using a stream insertion operator << we can write information to a file and using stream
extraction operator >> we can easily read information from a file.
1 #include<iostream>
#include <fstream>
2
using namespace std;
3
int main()
4
{
5
fstream new_file;
6
new_file.open("new_file",ios::out);
7
if(!new_file)
8 {
11 else
{
12
cout<<"New file created";
13
new_file.close(); // Step 4: Closing file
14
}
15
return 0;
16
}
17
18
Output:
Explanation
In the above example we first create an object to class fstream and name it ‘new_file’. Then
we apply the open() function on our ‘new_file’ object. We give the name ‘new_file’ to the
new file we wish to create and we set the mode to ‘out’ which allows us to write in our file.
We use a ‘if’ statement to find if the file already exists or not if it does exist then it will going
to print “File creation failed” or it will gonna create a new file and print “New file created”.
Writing to a File
Example:
1 #include <iostream>
2 #include <fstream>
4 int main()
5 {
6 fstream new_file;
new_file.open("new_file_write.txt",ios::out);
7
if(!new_file)
8
{
9
cout<<"File creation failed";
10
}
11
else
12 {
15 new_file.close();
}
16
return 0;
17
}
18
19
Output:
Explanation
Here we first create a new file “new_file_write” using open() function since we wanted to
send output to the file so, we use ios::out. As given in the program, information typed inside
the quotes after Insertion Pointer “<<” got passed to the output file.
1
#include <iostream>
2
#include <fstream>
3
using namespace std;
4
int main()
5 {
6 fstream new_file;
7 new_file.open("new_file_write.txt",ios::in);
8 if(!new_file)
9 cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>c
Output:
Explanation
In this example, we read the file that generated id previous example i.e. new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we print
the content of the file using extraction operator >>. The output prints without any space
because we use only one character at a time, we need to use getline() with a character
array to print the whole line as it is.
Close a File
It is simply done with the help of close() function.
Example
1
#include <iostream>
2
#include <fstream>
3 using namespace std;
4 int main()
5 {
6 fstream new_file;
7 new_file.open("new_file.txt",ios::out);
new_file.close();
8
return 0;
9
}
10
Output: