Introduction to C++ Programming(BPLCK205D)_Class PPT_Module-4
Introduction to C++ Programming(BPLCK205D)_Class PPT_Module-4
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
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
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.
#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
.
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
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.
Decimal
100.75 Hello India 100
Hex
100.75 Hello India 64
Scientific
1.007500e+02 Hello India 64
#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