0% found this document useful (0 votes)
5 views42 pages

Introduction to C++ Programming(BPLCK205D)_Class PPT_Module-4

This document provides an introduction to C++ programming with a focus on I/O streams, including the hierarchy of stream classes and their usage for file operations. It covers text and binary file handling, including how to read from and write to files using various stream classes such as ifstream, ofstream, and fstream. Additionally, it discusses unformatted and formatted I/O operations, along with examples to illustrate the concepts.

Uploaded by

Antheesh R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views42 pages

Introduction to C++ Programming(BPLCK205D)_Class PPT_Module-4

This document provides an introduction to C++ programming with a focus on I/O streams, including the hierarchy of stream classes and their usage for file operations. It covers text and binary file handling, including how to read from and write to files using various stream classes such as ifstream, ofstream, and fstream. Additionally, it discusses unformatted and formatted I/O operations, along with examples to illustrate the concepts.

Uploaded by

Antheesh R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 42

INTRODUCTION TO C++

PROGRAMMING
Subject Code: BPLCK205D
Module -4
I/O Streams
I/O Streams: C++ Class Hierarchy- File
Stream-Text File Handling- Binary File
Handling during file operations.
Textbook 2: Chapter 12(12.5) , Chapter 13 (13.6,13.7)
C++ streams and stream classes
 Stream is basically a channel on which data flow from
sender to receiver.
 Data can be sent out from the program on an output stream
or received into the program on an input stream.
 At the start of a program, the standard input stream "cin" is
connected to the keyboard and the standard output stream
"cout” is connected to the screen.(input and output streams
such as "cin" and "cout” are examples of stream objects)
 In C++ the entire I/O (Input/Output) system operates
through streams.
 A stream is connected to a physical device by the C++ input
output system (Popularly known as I/O system).
C++ streams and stream classes
• When C++ program begins four streams get opened - cin,
cout, cerr and clog.
Stream Meaning Physical device

cin Standard input Connected to Keyboard

cout Standard output Connected to Screen

cerr Standard error Connected to Screen

clog Buffer of error Connected to Screen

• The header file named iostream.h supports these I/O


operations.
C++ streams and stream classes
Libraries
• In C++ library is a collection of classes and functions.
• The standard I/O library is called iostream library.
Header file Meaning
iostream.h This is the most commonly used header file in any C# program. It
defines hierarchy of classes which includes collection of classes
from low level I/O to high level I/O.
iomanip.h It defines the set of manipulator. Using these manipulators the
streams can be modified and useful effects can be given.
strstream.h It includes set of classes with respect to character array. The
definition of various classes such as istrstream, ostrstream and
strstream is included in this header file.
fstream.h It includes set of classes that support file I/O. The definition of
various classes such as ifstream, ofstream and fstream is included in
this header file.
C++ streams and stream classes
Stream Classes
• The stream can represent file, console, and block of memory or
hardware device.
• The iostream library provides the common set of functions for
handling these streams.
C++ streams and stream classes
C++ Stream Classes Hierarchy
Classes for File Stream Operations

• To perform file I/O, need to include <fstream.h> in the program.


• It defines several classes, including ifstream, ofstream and fstream.
• These classes are derived from ios, so ifstream, ofstream and fstream
have access to all operations defined by ios.
• While using file I/O we need to do following tasks -
• To create an input stream, declare an object of type ifstream
• To create an output stream, declare an object of type ofstream.
• To create an input/output stream, declare an object of type fstream.
Classes for File Stream Operations
ofstream This stream class is used to write on files.

ifstream This stream class is used to read from files.

fstream This stream class is used for both read and write

from/to files.

• The file operations are associated with the object of one of the classes .
• ifstream
• ofstream
• fstream
• Hence an object is created of the corresponding class.
• The file can be opened by the function called open().
Classes for File Stream Operations

The syntax of file open is


open(filename,mode)
• The filename is a null terminated string that represents the name of the
file that is to be opened.
• The mode is optional parameter and is used with the flags as
Classes for File Stream Operations
ios::in Open for input operation.
iosout Open for output operation.
ios::binary Open for binary operations.

ios::ate If this flag is set then initial position is set at the end of the file
otherwise initial position is at the beginning of the file.

ios:app The output operations are appended to the file. This is an appending
mode. That means contents are inserted at the end of the file.

ios::trunc The contents of preexisting file get destroyed and it is replaced by


new one.
Open Text File Operation
The program creates a file called output.txt and writes the
message "Writing...Tested OK!!!" in that file. At the end of the
program the file is closed.

#include <iostream>
#include <fstream>
using namespace std;
int main();
{
ofstream fobj; //creating object
fobj.open ("output.txt"); //opening the file using object
fobj << "Writing... Tested OK!!!\n"; //writing to the file
fobj.close();//closing the file
return 0;
}
Classes for File Stream Operations

Close File Operation


To close the file the member function close() is used. The close function takes no
parameter and returns no value.
Read a Text File Operation
Example-1: Write a C++ program to read the contents of a text file
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std; Output
int main() The Contents of
{ the file are...
ifstream in;
Statement 1
char Data[80];
in.open("Sample.txt");
Statement 2
if (!in) Statement 3
{ Statement 4
// Print an error and exit Statement 5
cerr << "Sample.txt could not be opened for reading!" << endl; Statement 6
exit(1); Statement 7
}
cout<<"The Contents of the file are...." <<endl;
while(in)
{
in.getline(Data,80);
Note : The Sample.txt file is already created
cout<<"\n"<<Data;
}
with the data as obtained in above output.
in.close();
return 0; }
Text File Operation
Example-2: Write a program that reads an array of number from file and creates
another two files store the odd number in one file and even numbers in another file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream out_obj;
int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[10];
out_obj.open("input.dat");
out_obj.write((char *)&a, sizeof(a));
out_obj.close();
ifstream in_obj;
ofstream fp1,fp2;
in_obj.open("input.dat");
in_obj.read((char *)&b,sizeof(b)); //storing the values file in b[]
Text File Operation

fp1.open("Even.dat"); cout<<"\n The contents of even file are ..."<<endl;


fp2.open("Odd.dat"); while(fp) //reading even file
for(int i=0;i<10;i++) {
{ fp.get(ch);
if((b[i]%2)==0) cout<<ch;
fp1<<b[i]<<" "; //writing to even file }
else fp.close();
fp2<<b[i]<<" "; //writing to odd file fp.open("Odd.dat");
} cout<<"\n The contents of odd file are ..."<<endl;
in_obj.close(); while(fp)//reading odd file
fp1.close(); {
fp2.close(); fp.get(ch);
cout<<ch; Output
ifstream fp; The contents of even file
char ch; }
fp.close(); are ...
fp.open("Even.dat");
return 0; 2 4 6 8 10
} The contents of odd file
are ...
13579
Finding the End of the File (EOF)

• For finding end of the file eof() function is uses.


• This function is a member function of ios class.
• If end of file is encountered then it returns a non-zero value.
For example
if (seqfile. eof () != 0)
{
cout << " You are at the end of the file";
}
Open Binary File
// 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);

ofstream MCA_StudFile_Out("MCA.dat", ios::out | ios::binary | ios::trunc);


ifstream MCA_StudFile_In;
MCA_StudFile_In.open("MCA.dat", ios::in | ios::binary);
Read & Write Binary File
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.


Closing Binary File
Closing Binary Files
Closing of binary fi les is similar to closing text fi les. A
close() function is needed to close
the binary file.

.
MCA_StudFile_Out.close();
The syntax for closing a fi le is
FileObject.close()
It also
Binary File: Example program
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";
}
Binary File: Example program
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()) OUTPUT:
cout << "File write failed"; Enter roll no.: 1
cout << "Do you want to continue? (y/n): "; Enter name: Lara
cin >> Continue; Enter address: West Indies
} while(Continue != 'n'); Do you want to continue? (y/n): y
MCA_StudFile_Out.close(); Enter roll no.: 2
return 0; Enter name: Ranatunga
} Enter address: Sri Lanka
Do you want to continue? (y/n): n
Reading from Binary File: Example program
Reading from a binary file int main()
//ReadFile.cpp {
#include <iostream> struct student MCA Student In;
#include <fstream>
ifstream MCA_StudFile_In("MCA.dat", ios::in |
#include <string>
ios::binary);
using namespace std;
while(!MCA_StudFile_In.eof())
struct student
{ {
int RollNo; MCA_StudFile_In.read((char*) &MCA_Student_In,
char Name[30]; sizeof(struct student));
char Address[40]; if(MCA_StudFile_In.fail())
}; break;
void WriteStudent(student TempStud) WriteStudent(MCA_Student_In);
{ }
cout << "\n The roll no.: "; MCA_StudFile_In.close();
cout << TempStud.RollNo; return 0;
cout << "\n The name: "; }
Output
cout << TempStud.Name; The roll no.: 1
cout << "\n The address: "; The name: Lara
cout << TempStud.Address; The address: West Indies
cout << "\n"; The roll no.: 2
} The name: Ranatunga
The address Sri Lanka
Unformatted I/O

There are various functions for unformatted I/O and these are
i. get and put
ii. getline
iii.ignore
iv.write
Unformatted I/O
get and put functions
• The get function is used for reading the data through keyboard and put
function is for displaying the data on console.
Example
Read a character and write the character on the console
get(char*)
get(void)
put(char ch)
• The get function will be written along with cin and put function will be
along with the cout statement.
Unformatted I/O
Example -2 : To accepting a single
Example - 1
character and displaying it we can also use
#include <iostream> get and put functions for handling the
stream of characters.
using namespace std; #include <iostream>
int main() { using namespace std;
int main() {
char ch;
char s;
cout<<"\n Enter some character: "; cout<<"\n Enter a string: ";
cin.get(ch); while(s!='\n')
cout<<"\n You have entered ...\n"; {
cin.get(s); Output
cout.put(ch); Enter a string: Hello
cout.put(s);
return 0; Output } friends
Enter some character: a Hello friends
} return 0;
You have entered ...
}
a
Unformatted I/O
getline function
• Read few sentences from a stream getline() function is used.
• It can read till it encounters newline or sees a delimiter provided by user.
Syntax
getline (string& str, char delim);
getline (string& str);
Example
#include <iostream>
using namespace std;
int main() {
Output
Enter some text Hello How
char data[20];
are you?
cout<<"\n Enter some text: ";
Hello How are you?
cin.getline(data, 20);//reading a sentence
cout<<data; //displaying the sentence
return 0;
}
Unformatted I/O

getline function
Example (using terminating character ‘q’) Output
#include<iostream> Enter some sentences(type q) to
using namespace std; terminate
int main() Hello
{ How are you?
char data[50]; Enjoying
cout<<"\n Enter some sentences(type q) to and happy
terminate : "; q
cin.getline(data,50,'q');//reading a sentence hello
cout<<data; //displaying the sentence How are you?
return 0; Enjoying
} and happy
Unformatted I/O
ignore function
• The ignore function extracts the character from the input sequence and discard them.
#include <iostream>
using namespace std;
int main()
{
int num;
char s[10];
cout<<"\n Enter some number:“;
cin>>num;
cin.ignore();
cout<<"\n Enter some string: ";
cin.getline(s, 10);
cout<<"\n You have entered ...\n";
cout<<num;
cout<<"\n"<<s;
return 0;
}
Write function Unformatted I/O
• The write function is used to write the data.

Syntax

write((const char *buf, stream, size num);

buf represents the data to be written and num represents the size of that data.
#include <iostream>
#include<cstring>//for using strlen function
using namespace std;
int main() {
char str[20];
cout<<"\n Enter some string: ";
cin.getline(str, 20);
int n=strlen(str);//strlen function calculates length of string
cout<<"\n You have entered following string... \n";
cout.write(str,n);
return 0; }
Formatted I/O
• A set of format flags that control the way information is formatted.
• The ios class declares the values that are used to set or clear the format
flags.

Flags Meaning
skipws If this flag is set then leading white spaces are discarded (skipped). On clearing this
flag the leading white spaces are not discarded.
left On setting this flag the output becomes left justified.
right On setting this flag the output becomes right justified.
internal If it is set then numeric value is padded to fill the field between any sign or base
character and number.
oct It is set means numeric values are outputted in octal.
dec It is set means numeric values are outputted in decimal.
Formatted I/O
• A set of format flags that control the way information is formatted.
• The ios class declares the values that are used to set or clear the format
flags.

hex It is set means numeric values are outputted in hex.


showbase If set then it shows base indicator (for example OX for hex).
showpos It shows + sign before positive numbers.
showpoint On set it shows decimal point and trailing zeros for all floating point numbers.
scientific On set it shows exponential format on floating point numbers.
fixed On set it shows fixed format on floating point numbers.
boolalpha Booleans can be set using true or false.
uppercase On setting this flag upper case A-F are used for hex values and E for scientific
values.
Formatted I/O
#include <iostream>
using namespace std;
int main()
{
cout<<" Without applying format\n\n";
cout << 100.75 << " Hello India " << 100 << "\n";
cout << 10 <<" " << -10 << "\n";
cout << 100.0 << "\n\n";
cout<<" Decimal \n\n";
cout.unsetf(ios::dec);
cout << 100.75 << " Hello India " << 100 << "\n\n";
cout<<" Hex \n\n";
cout.setf(ios::hex);
cout << 100.75 << " Hello India " << 100 << "\n\n";
cout<<" Scientific\n\n";
cout.setf(ios::scientific);
cout << 100.75 << " Hello India " << 100 << "\n\n";
Formatted I/O
cout<<"Shows + sign before positive numbers";
cout.setf(ios::showpos);
cout << 10;
cout<<" show point\n\n";
cout.setf(ios::showpoint);
cout << 100.0 << "\n\n";
cout<<" Shows fixed format on floating point numbers\n\n";
cout.setf(ios::fixed);
cout<< 100.0<<"\n\n";
cout<< 100.0<<"\n\n";
return 0;
}
Formatted I/O
OUTPUT:
Without applying format
100.75 Hello India 100
10 -10
100

Decimal
100.75 Hello India 100

Hex
100.75 Hello India 64

Scientific
1.007500e+02 Hello India 64

Shows + sign before positive numbers a show point


+1.000000e+02

Shows fixed format on floating point numbers


+0x1.9p+6
+0x1.9p+6
Formatted I/O
Program illustrates the use of width, precision and fill functions
#include <iostream>
using namespace std;
int main() {
cout << "ABCD "<<"\n";
cout.width(10);
cout<<"ABCD "<<"\n";//sets right justified text
cout.fill('*'); // set fill character
cout.width(10); // set width
cout<<"ABCD"<<"\n"; // right justified text with preceding *
//hence the total number of characters are 10
cout.setf(ios::left); // left justify
cout.width(10); // set width
cout.precision(10); //set 10 digits of precision
cout << 10.203040 << "\n";
cout.precision(4); // set 4 digits of precision
cout << 102.0304050 << "\n";
cout.width(10);
cout.fill('*');
cout <<""; //simply prints * 10 times
return 0;
}
Output with Manipulators
• Manipulators are the operators in C++ that are used for formatting the output &
commonly used manipulators are setw, endl and setfill.
• The setw is used to set the minimum field width & defined in <iomanip.h> file.
#include <iostream.h> cout<<"Using setw(20)\n";
#include<iomanip.h> cout<<setw(20)<<a<<"\n";
#include<conio.h> cout<<setw(20) <<b<<"\n";
void main() cout<<setw(20)<<c<<"\n";
{ cout<<"Using setw(10)\n";
clrscr(); cout<<setw(10)<<a<<"\n";
int a=4444,b=22,c=333; cout<<setw(10) <<b<<"\n";
cout<<"Using setw(30)\n"; cout<<setw(10)<<c<<"\n";
cout<<setw(30)<<a<<"\n"; getch();
cout<<setw(30) <<b<<"\n"; }
cout<<setw(30)<<c<<"\n";
cout<<"Using setw(20)\n";
cout<<setw(20)<<a<<"\n";
cout<<setw(20) <<b<<"\n";
Output with Manipulators
• The functionality of endl is similar to "\n" i.e. newline character.

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout<<"This is first line"<<endl;
cout<<"This is second line"<<endl;
cout<<"This is third line"<<endl;
cout<<"This is forth line"<<endl;
return 0;
}
Output with Manipulators
• The setfill manipulator is used to fill the fields entirely using some
character specified within it.

#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int a=4444,b=22,c=333;
cout<<setw(10)<<setfill('*')<<a<<endl;
cout<<setw(10)<<setfill('*')<<b<<endl;
cout<<setw(10)<<setfill('*')<<c<<endl;
return 0;
}
Textbooks
1. Bhushan Trivedi, “Programming with ANSI C++”, Oxford Press,
Second Edition, 2012.
2. Balagurusamy E, “Object Oriented Programming with C++”, Tata
McGraw Hill Education Pvt. Ltd, Fourth Edition, 2010.
Weblinks and Video Lectures (e-Resources):
1. Basics of C++ :
https://www.youtube.com/watch?v=BClS40yzssA
2. Functions of C++ : https://www.youtube.com/watch?v=p8ehAjZWjPw
Tutorial Link:
1. https://www.w3schools.com/cpp/cpp_intro.asp
2. https://www.edx.org/course/introduction-to-c-3
42

Thank you

You might also like