OOP Lab 14
OOP Lab 14
Lab 14
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 −
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.
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
4
ios::out
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
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.
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
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.
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
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];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
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.