0% found this document useful (0 votes)
9 views

Week 13 File Handing

Uploaded by

mianh2221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Week 13 File Handing

Uploaded by

mianh2221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Object Oriented Programming

Week 13

Lecture 1 & 2

File Handling in C++

Files are used to store data in a storage device permanently. File handling provides a mechanism
to store the output of a program in a file and to perform various operations on it.

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 fstream base and from the corresponding iostream class. These
classes, designed to manage the disk files, are declared in fstream and therefore we must include
fstream 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:

 Creating a file: open()

Page 1 of 12
Object Oriented Programming

 Reading data: read()


 Writing new data: write()
 Closing a file: close()

Moving on with article on File Handling in C++

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.

We can open a file using any one of the following methods:


1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.

To open a file use

open() function

Syntax

void open(const char* file_name,ios::openmode mode);

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
in Opens the file to read(default for ifstream)
out Opens the file to write(default for ofstream)

Page 2 of 12
Object Oriented Programming

binary Opens the file in binary mode


Opens the file and appends all the outputs at the
app
end
Opens the file and moves the control to the end
ate
of the file
trunc Removes the data in the existing file
nocreate Opens the file only if it already exists
noreplace Opens the file only if it does not already exist

Example

fstream new_file;

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.

Default Open Modes :

 ifstream ios::in
 ofstream ios::out
 fstream ios::in | ios::out

We can combine the different modes using or symbol | .

Example

ofstream new_file;

Page 3 of 12
Object Oriented Programming

new_file.open(“new_file.txt”, ios::out | ios::app );

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.

Example of opening/creating a file using the open() function

#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}
Output:

Page 4 of 12
Object Oriented Programming

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”.

Moving on with article on File Handling in C++

Writing to a File

Example:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}

Page 5 of 12
Object Oriented Programming

return 0;
}
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.

Moving on with this article on File Handling in C++

Reading from a File

Example

#include <iostream>
#include <fstream>
using namespace std;

Page 6 of 12
Object Oriented Programming

int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
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.

Moving on with this article on File Handling in C++

Close a File

It is simply done with the help of close() function.

Syntax: File Pointer.close()

Example

#include <iostream>

Page 7 of 12
Object Oriented Programming

#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Output:

The file gets closed

//C++ program to write text in file.

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream file; //object of fstream class

//opening file "abc.txt" in out(write) mode

file.open("C:\\Users\\hp\\Desktop\\abc.txt",ios::out);

if(!file)

cout<<"Error in creating file!!!"<<endl;

return 0;

Page 8 of 12
Object Oriented Programming

cout<<"File created successfully."<<endl;

//write text into file

cout<<"write text in the file..."<<endl;

char ch[600];

cin>>ch; //for without spaces

//gets(ch); // for including spaces file<<ch;

//closing the file

file.close();

return 0;

Using cin>> command it will not accept the spaces when writing any string in the text file as
shown in the output:

Using gets () command it will accept the spaces when writing any string in the text file as shown
in the output:

Page 9 of 12
Object Oriented Programming

Write the City names in the file shown below:

#include <iostream>

#include <fstream>

using namespace std;

int main()

char city[100];

ofstream file; //object of fstream class

//opening file "abc.txt" in out(write) mode

file.open("C:\\Users\\hp\\Desktop\\abc.txt",ios::out);

if(!file)

cout<<"Error in creating file!!!"<<endl;

return 0;

cout<<"File created successfully."<<endl;

//write text into file

for (int i = 0;i<5;i++)

cout<<"enter city name..."<<endl;

cin>>city;

file<<city<<"\n";

file.close();

Page 10 of 12
Object Oriented Programming

return 0;

Output:

Printing City Names written in the Text Tile;

#include <iostream>

#include <fstream>

using namespace std;

int main()

char city[50];

ifstream file;

//again open file in read mode

file.open("C:\\Users\\hp\\Desktop\\abc.txt",ios::in);

if(!file)

Page 11 of 12
Object Oriented Programming

cout<<"Error in opening file!!!"<<endl;

return 0;

//read untill end of file is not found.

char ch; //to read single character

cout<<"Text Written in the Text File "<<endl;;

while(!file.eof())

file>>city; //read single character from file

cout<<city<<endl;

file.close(); //close file

return 0;

Output:

Page 12 of 12

You might also like