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

Module-5

Module 5 covers I/O streams in C++, detailing the use of fstream, ifstream, and ofstream classes for file operations. It explains how to create, open, read from, and write to files, along with examples of text and binary file handling. The module also outlines various file operation modes and provides syntax for implementing these functionalities.
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)
0 views

Module-5

Module 5 covers I/O streams in C++, detailing the use of fstream, ifstream, and ofstream classes for file operations. It explains how to create, open, read from, and write to files, along with examples of text and binary file handling. The module also outlines various file operation modes and provides syntax for implementing these functionalities.
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
You are on page 1/ 11

Module 5 – I/O Streams

DAYANANDA SAGAR COLLEGE OF ENGINEERING


Shavige Malleshwara Hills, Kumaraswamy Layout, Bengaluru-560078
(An Autonomous Institution affiliated to VTU, Belagavi)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Module 5

Streams in C++ :-

We give input to the executing program and the execution program gives back the output. The
sequence of bytes given as input to the executing program and the sequence of bytes that
comes as output from the executing program are called stream. In other words, streams are
nothing but the flow of data in a sequence.
The input and output operation between the executing program and the devices like keyboard
and monitor are known as “console I/O operation”. The input and output operation between the
executing program and files are known as “disk I/O operation”.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

ifstream:-

Department of CSE, DSCE Page 1


Module 5 – I/O Streams

• This class provides input operations.


• It contains open() function with default input mode.
• Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.

Syntax
ifstream object_name;
object_name.open(“file_name”);

ofstream:-
• This class provides output operations.
• It contains open() function with default output mode.
• Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.
Syntax
ofstream object_name;
object_name.open(“file_name”);

fstream:-
• This class provides support for simultaneous input and output operations.
• Inherits all the functions from istream and ostream classes through iostream.

Syntax
fstream object_name;
bject_name.open(“file_name”, mode);

Modes :

Member Stands
Constant For Access

File open for reading: the internal stream buffer supports input
in * input
operations.

File open for writing: the internal stream buffer supports


Out output
output operations.

Department of CSE, DSCE Page 2


Module 5 – I/O Streams

Member Stands
Constant For Access

Binary binary Operations are performed in binary mode rather than text.

Ate at end The output position starts at the end of the file.

All output operations happen at the end of the file, appending


App append
to its existing contents.

Any contents that existed in the file before it is open are


Trunk truncate
discarded.

Default Open Modes :

ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Operation on Text File

There are different types of operations that we can perform on a text file, they are:

• Create a new file.


• Open an existing file.
• Write to a file.
• Read from a file.
• Copy a file from one location to another.
• Rename a file.
• Delete a file.

Department of CSE, DSCE Page 3


Module 5 – I/O Streams

Create a new file

The program given below demonstrates how we can create a new text file in memory.

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream fs;

fs.open("e:/data.txt", ios::out);

if(fs.is_open()==0)

cout<<"Cannot open file";

fs.close();

return 0;

In the above program, we created fstream object fs and used the open() method to open a file
using the ios::out mode. After that, we used the is_open() method to check if the file opened
successfully or not. This method returns 1 if the file is opened; otherwise, it returns 0 when it
cannot open the file.

The close() method is used to close the file which is opened in the memory.

Department of CSE, DSCE Page 4


Module 5 – I/O Streams

Open an existing file

The program given below demonstrates how we can open an existing text file.
Example

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("e:/data.txt", ios::in);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
fs.close();
return 0;
}

In the above program, we have opened the file data.txt for reading using the read mode ios::in.

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

Let's see the simple example of writing to a text file testout.txt using C++ FileStream
programming.

Department of CSE, DSCE Page 5


Module 5 – I/O Streams

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Dayananda Sagar.\n";
filestream << "CSE Department.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}

Output:

The content of a text file testout.txt is set with the data:

Dayananda Sagar.

CSE Department.

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

Let's see the simple example of reading from a text file testout.txt using C++ FileStream
programming.

Department of CSE, DSCE Page 6


Module 5 – I/O Streams

#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}

Output:

Dayananda Sagar.

CSE Department.

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 <iostream>
Department of CSE, DSCE Page 7
Module 5 – I/O Streams

#include <fstream>
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;
}

Department of CSE, DSCE Page 8


Module 5 – I/O Streams

When the above code is compiled and executed, it produces the following sample input and
output −

Writing to the file


Enter your name: Zara
Enter your age: 9

Reading from the file


Zara
9

Reading and writing binary file in C/C++

Writing

To write a binary file in C++ use write method. It is used to write a given number of bytes on
the given stream, starting at the position of the "put" pointer. The file is extended if the put
pointer is currently at the end of the file. If this pointer points into the middle of the file,
characters in the file are overwritten with the new data.
If any error has occurred during writing in the file, the stream is placed in an error state.
Syntax of write method

ostream& write(const char*, int);

Reading

To read a binary file in C++ use read method. It extracts a given number of bytes from the given
stream and place them into the memory, pointed to by the first parameter. If any error is
occurred during reading in the file, the stream is placed in an error state, all future read operation
will be failed then.
gcount() can be used to count the number of characters has already read. Then clear () can be
used to reset the stream to a usable state.
Syntax of read method

Department of CSE, DSCE Page 9


Module 5 – I/O Streams

ifstream& write(const char*, int);

Reading and writing binary file

#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student wstu[3];
wstu[0].roll_no = 1;
wstu[0].name = "Ram";
wstu[1].roll_no = 2;
wstu[1].name = "Shyam";
wstu[2].roll_no = 3;
wstu[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &wstu[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1;
}

Department of CSE, DSCE Page 10


Module 5 – I/O Streams

ifstream rf("student.dat", ios::out | ios::binary);


if(!rf) {
cout << "Cannot open file!" << endl;
return 1;
}
Student rstu[3];
for(int i = 0; i < 3; i++)
rf.read((char *) &rstu[i], sizeof(Student));
rf.close();
if(!rf.good()) {
cout << "Error occurred at reading time!" << endl;
return 1;
}
cout<<"Student's Details:"<<endl;
for(int i=0; i < 3; i++) {
cout << "Roll No: " << wstu[i].roll_no << endl;
cout << "Name: " << wstu[i].name << endl;
cout << endl;
}
return 0;
}

Output

Student’s Details:
Roll No: 1
Name: Ram
Roll No: 2
Name: Shyam
Roll No: 3
Name: Madhu

Department of CSE, DSCE Page 11

You might also like