0% found this document useful (0 votes)
79 views26 pages

OOP Lecture Notes: File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views26 pages

OOP Lecture Notes: File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Genba Sopanrao Moze College Of Engineering, Balewadi - Pune Department of

MCA, F.Y SEM – I, Object Oriented Programming

Object Oriented Programming


[310903] LECTURE NOTES

MCA I YEAR – SEM (I)(2022-2023)

DEPARTMENT OF MCA

GENBA SOPANRAO MOZE COLLEGE OF ENGINEERING


S. No. 25/1/3, Balewadi-Baner, Pune- 411 045

(Approved by AICTE and Govt. of Maharashtra, Affiliated to Savitribai Phule Pune University)

Prepared by , Prof. Priyanka Yeole (MCA) Page 1


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
Unit – VI
Files handling

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:

To develop an ability to write programs in C++ for problem solving.

COURSE OUTCOMES:

CO6: Percept the utility of OOP for advanced programming.

Prepared by , Prof. Priyanka Yeole(MCA) Page 2


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

Ifstream

The fstream library allows us to work with files.

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

ofstream Creates and writes to files

ifstream Reads from files

fstream A combination of ofstream and ifstream: creates, reads, and


writes to files

Create and Write To a File

To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example

Prepared by , Prof. Priyanka Yeole(MCA) Page 3


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

#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;

// Read from the text file


ifstream MyReadFile("filename.txt");

// 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;
}

// Close the file


MyReadFile.close();

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.

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.

Prepared by , Prof. Priyanka Yeole(MCA) Page 4


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
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.

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 −

Prepared by , Prof. Priyanka Yeole(MCA) Page 5


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
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.
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.
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;

Prepared by , Prof. Priyanka Yeole(MCA) Page 6


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

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

Prepared by , Prof. Priyanka Yeole(MCA) Page 7


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
The file-position pointer is an integer value that specifies the location in the file as a number of
bytes from the file's starting location. Some examples of positioning the "get" file-position pointer
are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

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 −

Sr.No. Stream Definition

1 basic_istream It is used in an Input stream

2 basic_iostream It is used in an Input/output stream

Classes
The classes of istram should be as follows.

Sr.No. Classes Definition

1 istream It is used in an Input stream

2 iostream It is used in an Input/output stream

3 wistream It is used in an Input stream (wide)

4 wiostream It is used in an Input/output stream (wide)


Input manipulators (functions)
Sr.No. Functions Definition

1 ws It is used to extract whitespaces

Prepared by , Prof. Priyanka Yeole(MCA) Page 8


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

C++ Stream Classes Structure

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.

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.

Prepared by , Prof. Priyanka Yeole(MCA) Page 9


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

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

Input and output operation

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

opening along with the file name.

There are basically 3 default modes which are used while opening a file in C++:

• ofstreamios: : out

• fstreamios: : in | ios: : out

• ofstreamios : :out

Syntax:

void open(filename, ios: : openmodemode_name);

2. Read the Information from The File


We can simply read the information from the file using the operator ( >> ) with the name of the

file. We need to use the fstream or ifstream object in C++ in order to read the file. Reading of the

Prepared by , Prof. Priyanka Yeole(MCA) Page 11


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
file line by line can be done by simply using the while loop along with the function of ifstream

‘getline()’.

3. Close the File


As we all know about the C++ memory management, as the program terminates, it frees all the

allocated memory and the used resources. But still it is considered to be a good practice to close

the file after the desired operation is performed.

Syntax:

void close();

xamples of C++ Read File


Below given are the few examples along with their outputs to demonstrate how the file read

operation is performed in C++ :

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.

Prepared by , Prof. Priyanka Yeole(MCA) Page 13


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
seekg(), tellg(), seekp(), tellp()

In C++ we have a get pointer and a put pointer for getting (i.e. reading) data from a file and

putting(i.e. writing) data on the file respectively.

seekg() is used to move the get pointer to a desired location with respect to a reference point.

Syntax: file_pointer.seekg (number of bytes ,Reference point);

Example: fin.seekg(10,ios::beg);

tellg() is used to know where the get pointer is in a file.

Syntax: file_pointer.tellg();

Example: int posn = fin.tellg();

seekp() is used to move the put pointer to a desired location with respect to a reference point.

Syntax: file_pointer.seekp(number of bytes ,Reference point);

Example: fout.seekp(10,ios::beg);

tellp() is used to know where the put pointer is in a file.

Syntax: file_pointer.tellp();

Example: int posn=fout.tellp();

The reference points are:

ios::beg – from beginning of file

ios::end – from end of file

ios::cur – from current position in the file.

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:

Syntax: open (filename, mode);

There are some mode flags used for file opening. These are:

Prepared by , Prof. Priyanka Yeole(MCA) Page 14


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
• ios::app: append mode.
• ios::ate: open a file in this mode for output and read/write control to the end of the file.
• ios::in: open a file in this mode for reading.
• ios::out: open a file in this mode for writing.
• ios::trunk: when any file already exists, its contents will be truncated before the file
opening.

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:

// C++ program to demonstrate cin.get()

#include <iostream>

using namespace std;

int main()

char name[25];

cin.get(name, 25);

cout << name;

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:

Prepared by , Prof. Priyanka Yeole(MCA) Page 15


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
Syntax:
istream& getline(istream& is, string& str, char delim)

puts()

The puts() function in C++ writes a string to stdout.

puts() prototype

int puts(const char *str);

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

str: The string to be written.


puts() Return value

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;
}

When you run the program, the output will be:

Happy New Year

Prepared by , Prof. Priyanka Yeole(MCA) Page 16


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
Happy Birthday

Command line arguments


It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important
for your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to
the number of arguments passed, and argv[] is a pointer array which points to each argument
passed to the program. Following is a simple example which checks if there is any argument
supplied from the command line and take action accordingly −
Example

#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

Prepared by , Prof. Priyanka Yeole(MCA) Page 17


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
us re-write above example once again where we will print program name and we also pass a
command line argument by putting inside double quotes −
Example

#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!";

Prepared by , Prof. Priyanka Yeole(MCA) Page 18


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
cout << "I am learning C++";
return 0;
}

Early Binding and Late Binding:-

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

Error Handling in File I/O

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.

• When trying to open a file for reading might not exist.


• When trying to read from a file beyond its total number of characters.
• When trying to perform a read operation from a file that has opened in write mode.
• When trying to perform a write operation on a file that has opened in reading mode.
• When trying to operate on a file that has not been open.

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.

Flag Bit Meaning


badbit 1 when a fatal I/O error has occurred, 0 otherwise.
failbit 1 when a non-fatal I/O error has occurred, 0 otherwise
goodbit 1 when no error has occurred, 0 otherwise
eofbit 1 when end-of-file is encountered, 0 otherwise.
Prepared by , Prof. Priyanka Yeole(MCA) Page 20
Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
We use the above flag bits to handle the errors during the file operations.

Error Handling During the File Operations in C++


The C++ programming language provides several built-in functions to handle errors during file
operations. The file error handling

The following are the built-in functions to handle file errors.

Function Return Value


int bad() It 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 fail( ) It returns a non-zero (true) value when an input or output operation has failed.
int It returns a non-zero (true) value when no error has occurred; otherwise returns zero
good() (false).
int eof( ) It returns a non-zero (true) value when end-of-file is encountered while reading;
otherwise returns zero (false).

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.

Let's look at the following code.

Example - Code to illustrate the bad( ) function


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file;
file.open("my_file.txt", ios::out);

string data;

file >> data;

if(!file.bad()){
cout << "Operation not success!!!" << endl;
cout << "Status of the badbit: " << file.bad() << endl;
}

Prepared by , Prof. Priyanka Yeole(MCA) Page 21


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
else {
cout << "Data read from file - " << data << endl;
}

return 0;
}
Output

int fail( )
The fail( ) function returns a non-zero value when an input or output operation has failed.

Let's look at the following code.

Example - Code to illustrate the fail( ) function


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file;
file.open("my_file.txt", ios::out);

string data;

file >> 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;

Prepared by , Prof. Priyanka Yeole(MCA) Page 22


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
}

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

Let's look at the following code.

Example - Code to illustrate the eof( ) function


#include <iostream>
#include <fstream>

using namespace std;

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;
}

Prepared by , Prof. Priyanka Yeole(MCA) Page 23


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
Output

int good( )
The good( ) function returns a non-zero (true) value when no error has occurred; otherwise
returns zero (false).

Let's look at the following code.

Example - Code to illustrate the good( ) function


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file;
file.open("my_file.txt", ios::in);

cout << "goodbit: " << file.good() << endl;

string data;

cout << endl << "Data read from file:" << endl;
while(!file.eof()){
file >> data;
cout << data << " ";
}
cout << endl;

return 0;
}

Prepared by , Prof. Priyanka Yeole(MCA) Page 24


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management
Output

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

Prepared by , Prof. Priyanka Yeole(MCA) Page 25


Genba Sopanrao Moze College Of Engineering, Balewadi - Pune
Department of MCA, F.Y SEM – I, Software Engineering and project Management

UNIT _ 6

Sample Questions:

1. What are stream classes? Explain any two input and output functions with example

2. What are manipulators? Explain user defined manipulators with example

3. What are different modes of file operations in C++

Prepared by , Prof. Priyanka Yeole(MCA) Page 26

You might also like