OOP Lecture Notes: File Handling
OOP Lecture Notes: File Handling
DEPARTMENT OF MCA
(Approved by AICTE and Govt. of Maharashtra, Affiliated to Savitribai Phule Pune University)
Ifstream, of stream, istream, ostream and fstream classes and their hierarchy. Input and output
operation - open() ,get(), getline(), read(), seekg() and tellg() AND put(), seekp(), tellp(),and
write() functions, Command-Line Arguments, Printer output, Early vs. Late Binding, Error
Handling in File I/O
COURSE OBJECTIVES:
COURSE OUTCOMES:
Ifstream
To use the fstream library, include both the standard <iostream> AND the <fstream> header file:
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create, write or read
files:
Class Description
To create a file, use either the ofstream or fstream class, and specify the name of the file.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file.
Note that we also use a while loop together with the getline() function (which belongs to
the ifstream class) to read the file line by line, and to print the content of the file:
Example
// Create a text string, which is used to output the text file
string myText;
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
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.
1 ofstream
This data type represents the output file stream and is used to create files and to write
information to 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 −
#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.
File Position Pointers
Both istream and ostream provide member functions for repositioning the file-position pointer.
These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified
to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning
relative to the beginning of a stream, ios::cur for positioning relative to the current position in a
stream or ios::end for positioning relative to the end of a stream.
istream
The Istream used for header providing the standard input and combined input/output stream
classes.
Class templates
The class templates of istream should be as follows −
Classes
The classes of istram should be as follows.
In 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.
Example
OUT STREAM
COUT
#include <iostream>
using namespace std;
int main(){
cout<<"This output is printed on screen";
}
Output
This output is printed on screen
PUTS
#include <iostream>
using namespace std;
int main(){
puts("This output is printed using puts");
}
Output
This output is printed using puts
IN STREAM
CIN
#include <iostream>
using namespace std;
int main(){
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is "<
Output
Enter a number 3453
Number entered using cin is 3453
gets
#include <iostream>
using namespace std;
int main(){
char ch[10];
Prepared by , Prof. Priyanka Yeole(MCA) Page 10
Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}
Output
Enter a character array
thdgf
The character array entered using gets is :
thdgf
Read()
1. Opening the Already Created File
In order to read the information from the file, we need to first open it. The opening of the file is
done using ofstream or fstream object of the file. Files in C++ can be opened in different modes
depending on the purpose of writing or reading. Hence, we need to specify the mode of file
There are basically 3 default modes which are used while opening a file in C++:
• ofstreamios: : out
• ofstreamios : :out
Syntax:
file. We need to use the fstream or ifstream object in C++ in order to read the file. Reading of the
‘getline()’.
allocated memory and the used resources. But still it is considered to be a good practice to close
Syntax:
void close();
Example #1
Code:
#include <iostream>
#include <fstream>
using namespace std;
intmain(){
char data[100];
// creating the file variable of the fstream data type for writing
fstreamwfile;
// opening the file in both read and write mode
wfile.open ("demo.txt", ios::out| ios::in );
// Asking the user to enter the content
cout<< "Please write the content in the file." <<endl;
// Taking the data using getline() function
cin.getline(data, 100);
Prepared by , Prof. Priyanka Yeole(MCA) Page 12
Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
// Writing the above content in the file named 'demp.txt'
wfile<< data <<endl;
// closing the file after writing
wfile.close();
//creating new file variable of data type 'ifstream' for reading
ifstreamrfile;
// opening the file for reading the content
rfile.open ("demo.txt", ios::in| ios::out );
// Reading the content from the file
rfile>> data;
cout<< data <<endl;
//closing the file after reading is done
rfile.close();
return 0;
}
Explanation: In the above example, we have created two file variables of ‘fstream’ and ‘ifstream’
data type for writing and reading of the file respectively. In order to read or write the file, we need
to first open the file using the open() function and define its mode. After opening, writing of the
content in the file is done through the ( << ) operator and the file is closed after writing using the
close() function. Now the file is opened again in order to read its content (using >> operator) and
display it on the console (using cout function). In order to release all the resources and free the
allocated memory close() function is used. 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.
In C++ we have a get pointer and a put pointer for getting (i.e. reading) data from a file and
seekg() is used to move the get pointer to a desired location with respect to a reference point.
Example: fin.seekg(10,ios::beg);
Syntax: file_pointer.tellg();
seekp() is used to move the put pointer to a desired location with respect to a reference point.
Example: fout.seekp(10,ios::beg);
Syntax: file_pointer.tellp();
In seekg() and seekp() if we put – sign in front of number of bytes then we can move backwards
open()
The first operation generally performed on an object of one of these classes to use a file is the
procedure known as opening a file. An open file is represented within a program by a stream, and
any input or output task performed on this stream will be applied to the physical file associated
with it. The syntax of opening a file in C++ is:
There are some mode flags used for file opening. These are:
get()
• cin.get() is used for accessing character array. It includes white space characters.
Generally, cin with an extraction operator (>>) terminates when whitespace is found.
However, cin.get() reads a string with the whitespace.
• Syntax:
cin.get(string_name, size);
Example 1:
#include <iostream>
int main()
char name[25];
cin.get(name, 25);
return 0;
Input:
Geeks for Geeks
Output:
Geeks for Geeks
getline()
The C++ getline() is a standard library function that is used to read a string or a line from an
input stream. It is a part of the <string> header. The getline() function extracts characters from
the input stream and appends it to the string object until the delimiting character is encountered.
While doing so the previously stored value in the string object str will be replaced by the input
string if any.
The getline() function can be represented in two ways:
puts()
puts() prototype
The puts() function takes a null terminated string str as its argument and writes it to stdout. The
terminating null character '\0' is not written but it adds a newline character '\n' after writing the
string.
A call to puts() is same as calling fputc() repeatedly.
The main difference between fputs() and puts() is the puts() function appends a newline character
to the output, while fputs() function does not.
It is defined in <cstdio> header file.
puts() Parameters
On success, the puts() function returns a non-negative integer. On failure it returns EOF and sets
the error indicator on stdout.
Example: How puts() function works
#include <cstdio>
int main()
{
char str1[] = "Happy New Year";
char str2[] = "Happy Birthday";
puts(str1);
/* Printed on new line since '/n' is added */
puts(str2);
return 0;
}
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
Output
$./a.out testing
The argument supplied is testing
Output
$./a.out testing1 testing2
Too many arguments supplied.
Output
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the
first command line argument supplied, and *argv[n] is the last argument. If no arguments are
supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space
then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
Output
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2
Printer output
The cout object, together with the << operator, is used to output values/print text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line at
the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
The binding means the process of converting identifiers into addresses. For each variables and
functions this binding is done. For functions it is matching the call with the right function
definition by the compiler. The binding is done either at compile time or at runtime.
Early Binding
This is compile time polymorphism. Here it directly associates an address to the function call.
For function overloading it is an example of early binding.
Example
#include<iostream>
using namespace std;
class Base {
public:
void display() {
cout<<" In Base class" <<endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" << endl;
}
};
int main(void) {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}
Output
In Base class
Late Binding
This is run time polymorphism. In this type of binding the compiler adds code that identifies the
object type at runtime then matches the call with the right function definition. This is achieved by
using virtual function.
Example
Prepared by , Prof. Priyanka Yeole(MCA) Page 19
Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
#include<iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout<<"In Base class" << endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" <<endl;
}
};
int main() {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}
Output
In Derived class
It's quite common that errors may occur during file operations. There may have different reasons
for arising errors while working with files. The following are the common problems that lead to
errors during file operations.
During the file operations in C++, the status of the current file stream stores in an integer flag
defined in ios class. The following are the file stream flag states with meaning.
int bad( )
The bad( ) function returns a non-zero (true) value if an invalid operation is attempted or an
unrecoverable error has occurred. Returns zero if it may be possible to recover from any other
error reported and continue operations.
int main()
{
fstream file;
file.open("my_file.txt", ios::out);
string data;
if(!file.bad()){
cout << "Operation not success!!!" << endl;
cout << "Status of the badbit: " << file.bad() << endl;
}
return 0;
}
Output
int fail( )
The fail( ) function returns a non-zero value when an input or output operation has failed.
int main()
{
fstream file;
file.open("my_file.txt", ios::out);
string data;
if(file.fail()){
cout << "Operation not success!!!" << endl;
cout << "Status of the failbit: " << file.fail() << endl;
}
else {
cout << "Data read from file - " << data << endl;
return 0;
}
Output
int eof( )
The eof( ) function returns a non-zero (true) value when end-of-file is encountered while reading;
otherwise returns zero (false).
int main()
{
fstream file;
file.open("my_file.txt", ios::in);
string data;
while(!file.eof()){
file >> data;
cout << "data read: " << data << " | eofbit: " << file.eof() << endl;
}
return 0;
}
int good( )
The good( ) function returns a non-zero (true) value when no error has occurred; otherwise
returns zero (false).
int main()
{
fstream file;
file.open("my_file.txt", ios::in);
string data;
cout << endl << "Data read from file:" << endl;
while(!file.eof()){
file >> data;
cout << data << " ";
}
cout << endl;
return 0;
}
int clear( )
The clear( ) function used to reset the error state so that further operations can be attempted.
• The above functions can be summarized as eof() returns true if eofbit is set; bad() returns
true if badbit is set. The fail() function returns true if failbit is set; the good() returns true
there are no errors. Otherwise, they return false.
• All the built-in function returns either non-zero to indicate true or zero to indicate false
UNIT _ 6
Sample Questions:
1. What are stream classes? Explain any two input and output functions with example