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

OOP Lab 14

Uploaded by

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

OOP Lab 14

Uploaded by

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

UNIVERSITY OF CHAKWAL

DEPARTMENT OF COMPUTER SCIENCE


(Object Oriented Programming)

Lab 14

Introduction to C++ File Handling

Lab Instructor: Engr. Samina Bilquees


Objectives
In this lab, you will learn:
 Reading File
 Writing data into the file
 Both reading and writing data into the file
File Handling

File handling in C++ is a mechanism to store the output of a program in a file and help perform various
operations on it. Files help store these data permanently on a storage device.

The term “Data” is commonly referred to as known facts or information. In the present era, data plays a
vital role. It helps to describe, diagnose, predict or prescribe. But to achieve all this, we need to store it
somewhere. You all would argue that there are so many text editors like ‘Notepad’ and ‘MS Office’,
which help us store data in the form of text. You are right! But here we are discussing at a level of
programming. In contrast, text editors like ‘Notepad’ and ‘MS Office’ are pre-built and cannot be
accessed at the programming level to store data. File Handling is a hot topic when it comes to storing such
programming data.

Almost every programming language has a ‘File Handling’ method to deal with the storage of data.
Now, This topic of file handling is further divided into sub-topics:

 Create a file
 Open a file
 Read from a file
 Write to a file
 Close a file

So far, we have been using 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 −

Sr.No Data Type & Description

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.

Example:

#include<iostream>

#include<fstream>
After including the header file, there comes a question saying do we need to create the file within the
program or else do we need to use an existing file. But this isn’t that difficult to answer because, in C++,
we get four different methods to handle files. Let’s discuss them one by one.

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.

Sr.No Mode Flag & Description

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 );
Program for Opening File:

1 #include<iostream>
2 #include<fstream>
3 using namespace std;
4 int main(){
5 fstream FileName;
6 FileName.open("FileName", ios::out);
7 if (!FileName){
8 cout<<"Error while creating the file";
9 }
10 else{
11 cout<<"File created successfully";
12 FileName.close();
13 }
14 return 0;
15 }
Explanation of above code

1. Here we have an iostream library, which is responsible for input/output stream.


2. We also have a fstream library, which is responsible for handling files.
3. Creating an object of the fstream class and named it as ‘FileName’.
4. On the above-created object, we have to apply the open() function to create a new file, and the
mode is set to ‘out’ which will allow us to write into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. We use the close() function on the object to close the file.
Output

File created successfully

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.

Program for Writing to File:

1 #include<iostream>
2 #include<fstream>
3 using namespace std;
4 int main() {
5 fstream FileName;
6 FileName.open("FileName.txt", ios::out);
7 if (!FileName) {
8 cout<<" Error while creating the file ";
9 }
10 else {
11 cout<<"File created and data got written to file";
12 FileName<<"This is a blog posted on Great Learning";
13 FileName.close();
14 }
15 return 0;
16 }
Explanation of above code

1. Here we have an iostream library, which is responsible for input/output stream.


2. We also have a fstream library, which is responsible for handling files.
3. Creating an object of the fstream class and named it as ‘FileName’.
4. On the above-created object, we have to apply the open() function to create a new file, and the
mode is set to ‘out’ which will allow us to write into the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Prints the message to console if the file exists/created.
8. Writing the data to the created file.
9. We use the close() function on the object to close the file.
Output

File created and data got written to file

Reading from a File

You read information from a file into your program using the stream extraction operator (>>) just as you
use that operator to input information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.

Program for Reading from File:

1 #include<iostream>
2 #include <fstream>
3 using namespace std;
4 int main() {
5 fstream FileName;
6 FileName.open("FileName.txt", ios::in);
7 if (!FileName) {
8 cout<<"File doesn’t exist.";
9 }
10 else {
11 char x;
12 while (1) {
13 FileName>>x;
14 if(FileName.eof())
15 break;
16 cout<<x;
17 }
18 }
19 FileName.close();
20 return 0;
21 }
Explanation of above code

1. Here we have an iostream library, which is responsible for input/output stream.


2. We also have a fstream library which is responsible for handling files.
3. Creating an object of the fstream class and named it ‘FileName’.
4. On the above-created object, we have to apply the open() function to create a new file, and the
mode is set to ‘in’ which will allow us to read from the file.
5. We use the ‘if’ statement to check for the file creation.
6. Prints the message to console if the file doesn’t exist.
7. Creating a character(char) variable with the named x.
8. Iterating of the file with the help of while loop.
9. Getting the file data to the variable x.
10. Here we are using if condition with eof() which stands for the end of the file to tell the compiler to
read till the file’s end.
11. We use the ‘break’ statement to stop the reading from file when it reaches the end.
12. The print statement to print the content that is available in the variable x.
13. We use the close() function on the object to close the file
Output

Hello World, Thank You for Visiting Great Learning.

Read and Write Example

Following is the C++ program which opens a file in reading and writing mode. After writing information
entered by the user to a file named afile.dat, the program reads information from the file and outputs it
onto the screen

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

int main () {
char data[100];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();
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.

You might also like