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

Module 4 C Module 4

Uploaded by

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

Module 4 C Module 4

Uploaded by

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

lOMoARcPSD|37698139

Module-4-C++ - Module 4

Introduction to C++ (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Nandini Patted ([email protected])
lOMoARcPSD|37698139

I/O Streams and File Stream

Module-4
I/ O Streams and File Stream
4.1 I/ O Streams
What are C++ streams?
 In C++, a str eam refer s to a sequence of char acter s that ar e tr ansferr ed
between the progr am and input/ output (I/ O) devices.
 Stream classes in C++ facilitate input and output oper ations on files and other
I/ O devices.
 These classes have specific featur es to handle progr am input and output,
making it easier to write portable code that can be used across multiple
platforms.
 To use str eams in C++, you need to include the appropriate header file. For
instance, to use input/ output str eams, you would include the iostr eam header
file. This libr ar y provides the necessary functions and classes to wor k with
str eams, enabling you to read and write data to and from files and other I/ O
devices.
 The I/ O system of C++ contains a set of classes that define the file handling
methods. These include ifstream, ofstream and fstream. These classes ar e
derived from fstreambase and from the corresponding iostream class as shown
in Fig. 4.1. These classes, designed to manage the disk files, are declared in
fstream and therefore, we must include this file in any program that uses files.

Fig. 4.1 Stream classes for file operations (contained in fstream file)

Dept. of CSE,RYMEC,Ballari Page 1

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Table 4.1 shows the details of file stream classes. Note that these classes contain
many more features.

4.2 C++ Stream Classes Hierarchy:


The I/ O hierarchy shown in Fig. 4.2 is usually mentioned without the prefix
basic_, that is, basic_ ios is usually referred to as ios. The ios_base class contains the
details not needed for templatization. basic_ios and its descendants are all templatized.
basic_streambuf provides the mechanism to access the stream using lower-level
functions. It also provides services to other classes.

Fig. 4.2 I/ O hierarchy

Dept. of CSE,RYMEC,Ballari Page 2

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

4.3 Text Files


4.3.1 Defining Files
Files can be defi ned in three possible types;
1) ifstream <fi lename> (input file stream)
2) ofstream <fi lename> (output file stream)
3) fstream <fi lename> (I/ O file stream)

 ifstream opens a file in read mode and ofstream opens it in write mode, whereas
fstream opens it in read–write mode.
 The ifstream file is a read-only file, and one can only read from the file defined as
ifstream.
 The ofstream file is an output-only file, and one can only write to the file defined
 as ofstream.
 The fstream file is used for both input and output.

4.3.2 Opening Files


 Files can be opened using constructors and open functions.
 Using constructors, one can open a file with a statement such as
ofstream EntryFile("FewLines.dat")
 The file modes have not been specified. It is assumed to be ios::out (output
mode) when the object of ofstream class (the EntryFile) is defined.
 Now, take a look at the following statement:
ifstream DisplayFile("FewLines.dat");
 Again, the file mode has not been specified. It is assumed to be ios::in (input
mode) for the objects of ifstream class (the DisplayFile) in this case.

4.3.3 Reading from and Writing to Files


 It is very simple to read from and write to a file. Overloaded << and >> operators
need to be used as they were used with cout and cin.

4.3.4 Closing Files


 The function close() is used without any arguments to close a file. The allocated
file handle is deallocated and the buffers are flushed when a file is closed.

Dept. of CSE,RYMEC,Ballari Page 3

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Example Program 1:
/ / WriteReadText.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string InputLine, OutputLine;
ofstream EntryFile("FewLines.dat")
cout << "Input :" << endl;
while(true)
{
cin >> InputLine;
if(InputLine == "End") break;
EntryFile << InputLine << endl; / / Writing to EntryFile
}
EntryFile.close();
cout << "Output: " << endl;
ifstream DisplayFile("FewLines.dat");
while(IDisplayFile.eof())
{
DisplayFile >> OutputLine;
cout << OutputLine << "\ n";
}
DisplayFile.close();
return 0;
}

Input
It was a fight
for pride and ego
for one
It was a fight for
duty and self-respect
for another
who won it at the End
Output
It
was
a
fight
...
who
won
it
at
the

Dept. of CSE,RYMEC,Ballari Page 4

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Note* : Using either << or >> will be a problem when a string contains spaces, as it
considers each item separ ated by a space as an individual item.

 Why does not the program display the original lines as they are in the output?
Why are the lines broken into words? It is because the bare ifstream object (such
as cin) is not capable of doing it. The problem of using an ifstream object in its
bare form (i.e., using >>) is that it cannot work with strings containing spaces.
 If a string contains spaces, each word is counted as a separate record. One needs
to use either get() and put() (for reading char by char) or use getline() function
for reading lines with spaces.

4.3.5 Using get() and put( )


 get() and put() functions are useful for reading from and writing to files
character by character.
Their syntax is as follows:
cin.get(ch) (reads a character from cin and stores what is read in ch)
cout.put(ch) (reads a character ch and writes to cout)

Example Program 2:
/ / GetPut.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include <iomanip>
int main()
{
char ch;
ofstream EntryFile("FewLines.dat");
while(true)
{
cin.get(ch);
if(ch == '$') break;
EntryFile << ch;
}
EntryFile.close();
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof())
{
/ / Do not skip white space
DisplayFile.unsetf(ios::skipws);
DisplayFile >> ch;
cout << ch;
}
DisplayFile.close();
return 0;
}

Dept. of CSE,RYMEC,Ballari Page 5

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Input
The battle
between One and Another
is
between light and darkness
between truthfulness and falsehood
between duty and ego
$
Output
The battle
between One and Another
is
between light and darkness
between truthfulness and falsehood
between duty and ego

4.3.6 Using getline( )


 getline() is useful for reading entire lines.
 One can even use cout and cin with getline() to provide the same result.
 Look at Program 3. The same getline() available with cin is also available to all
istream objects. It is also available to the DisplayFile().

Example Program 3:
/ / Getline.cpp
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
char InputLine[80], OutputLine[80];
ofstream EntryFile("FewLines.dat");
while(true)
{
cin.getline(InputLine, 80);
if(!strcmp(InputLine, "End")) break;
EntryFile << InputLine << endl;
}
EntryFile.close();
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof())
{
DisplayFile.getline(OutputLine, 80);
cout << OutputLine << endl;
}
DisplayFile.close();
return 0;
}

Dept. of CSE,RYMEC,Ballari Page 6

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Input
Imagination is
more important
than knowledge
End
Output
Imagination is more important than knowledge

 The only important part of this program involves using getline() function. When
the following statements are executed, the line (maximum 80 characters as
specified in the argument or until the carriage return is encountered) is read into
the input (if cin is used to invoke getline()) or read from the file (if file name is
used to invoke getline()).
cin.getline(InputLine, 80);
DisplayFile.getline(OutputLine, 80);
 One can try commenting the fi le generation code from this program, construct a
file using an editor, and see how the program outputs. The program will work
like a DOS-type command and display the contents of the file.

Dept. of CSE,RYMEC,Ballari Page 7

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

4.4 Binary Files


In this section, we will focus our concentration on binary files. These files are
more useful for storing structures of information.

4.4.1 Opening a Binary File


 A binary file can be opened using a constructor. The constructors for ofstream
and ifstream that we have seen so far are acceptable for text files.
 For binary files, another constructor with two arguments is needed. The first
argument is the name of the fi le and the second one is the file mode.
Look at the following statements, which are examples for both the methods.
/ / Using open methods
ofstream MCA_StudFile_Out;
MCA_StudFile_Out.open("MCA.dat", ios::out | ios::binary | ios::trunc);
/ / Using constructor
ifstream MCA_StudFile_In("MCA.dat", ios::in | ios::binary);
 An open function can also be used with a file to open a file. If ever we need to
open the same file using different modes, open() is useful.

4.4.2 Reading from and Writing to Binary Files


 Two member functions for ifstream and ofstream objects are useful in reading
and writing.Both of them have similar syntax. They are;
 OfstreamFileObject.write((char *) &<the object>, sizeof(<the same object>)) for
writing in the file and
 IfStreamFileObject.read((char *) &<the object>, sizeof(<the same object>)) for
reading from the file.
 It is important to understand that the file read and write is performed objectwise
and not elementwise.
 One reads the complete object from the file or writes the complete object to the
file using a single read or write.
 The object here can even be a struct variable such as struct student of Program 4.

4.4.3 Closing Binary Files


 Closing of binary files is similar to closing text files. A close() function is needed
to close the binary file.
The syntax for closing a file is
FileObject.close()
 It also deallocates the file handle and flushes the allocated buffers as in the case
of text files.

Dept. of CSE,RYMEC,Ballari Page 8

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Example Program 4: Writing to a binary file


/ / WriteFile.cpp
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
int RollNo;
char Name[30];
char Address[40];
};
void ReadStudent(student & TempStud)
{
cout << "\ n Enter roll no.: ";
cin >> TempStud.RollNo;
cout << "\ n Enter name: ";
cin >> TempStud.Name;
cout << "\ n Enter address: ";
cin >> TempStud.Address;
cout << "\ n";
}
int main()
{
struct student MCA_Student_Out;
ofstream MCA_StudFile_Out;
MCA_StudFile_Out.open("MCA.dat", ios::out | ios::binary | ios::trunc);
if(!MCA_StudFile_Out.is_open())
cout << "File cannot be opened \ n";
char Continue = 'y';
do
{
ReadStudent(MCA_Student_Out);
MCA_StudFile_Out.write((char*) &MCA_Student_Out, sizeof(struct
student));
if(MCA_StudFile_Out.fail())
cout << "File write failed";
cout << "Do you want to continue? (y/ n): ";
cin >> Continue;
} while(Continue != 'n');
MCA_StudFile_Out.close();
return 0;
}

Dept. of CSE,RYMEC,Ballari Page 9

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

Input
Enter roll no.: 1
Enter name: Bhagath
Enter address: INDIA
Do you want to continue? (y/ n): y
Enter roll no.: 2
Enter name: Subash
Enter address: INDIA
Do you want to continue? (y/ n): y
Enter roll no.: 3
Enter name: Azad
Enter address: Bharath
Do you want to continue? (y/ n): n

Example Program 5: Reading from a binary file


/ / ReadFile.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student
{
int RollNo;
char Name[30];
char Address[40];
};
void WriteStudent(student TempStud)
{
cout << "\ n The roll no.: ";
cout << TempStud.RollNo;
cout << "\ n The name: ";
cout << TempStud.Name;
cout << "\ n The address: ";
cout << TempStud.Address;
cout << "\ n";
}
int main()
{
struct student MCA Student In;
ifstream MCA_StudFile_In("MCA.dat", ios::in | ios::binary);
while(!MCA_StudFile_In.eof())
{
MCA_StudFile_In.read((char*) &MCA_Student_In, sizeof(struct
student));

Dept. of CSE,RYMEC,Ballari Page 10

Downloaded by Nandini Patted ([email protected])


lOMoARcPSD|37698139

I/O Streams and File Stream

if(MCA_StudFile_In.fail())
break;
WriteStudent(MCA_Student_In);
}
MCA_StudFile_In.close();
return 0;
}

Output
The roll no.: 1
The name: Lara
The address: West Indies
The roll no.: 2
The name: Ranatunga
The address Sri Lanka
The roll no.: 3
The name: Steffi
The address Germany

Dept. of CSE,RYMEC,Ballari Page 11

Downloaded by Nandini Patted ([email protected])

You might also like