SlideShare a Scribd company logo
Managing I/O Console
using C++
C++ Stream Classes
• Stream and stream classes : to implement I/O
operations with the console and disk files.
• It is a sequence of bytes(or interface)..
• It acts as a source from which input data can
be obtained.
• or as destination to which the output can be
sent.
• Source stream is called Input stream.
• Destination stream is called Output stream.
• Data in the Input stream can come from
Keyboard etc.
• Similarly, data in the output stream can go to
the screen.
• C++ provides standard iostream library to
operate with streams.
• Cin and cout are the predefined streams .
• If bytes flow from a device like a keyboard, a
disk drive, or a network connection etc. to
main memory, this is called input operation .
• and if bytes flow from main memory to a
device like a display screen, a printer, a disk
drive, or a network connection, etc., this is
called output operation.
• istream is a general purpose input stream. cin
is an example of an istream.
• ostream is a general purpose output stream.
cout is the example of ostream.
• ifstream is an input file stream. It is a special
kind of an istream that reads in data from a
data file.
• ofstream is an output file stream. It is a
special kind of ostream that writes data out to
a data file.
• C++ provides the following classes to perform
output and input of characters to/from files:
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.
Console I/O operations
There are mainly two types of console I/O
operations form:
• Unformatted console input output
• Formatted console input output
Unformatted input output operations
The following are operations of unformatted
input / output operations:
A) void get()
• It is a method of cin object used to input a
single character from keyboard. But its main
property is that it allows wide spaces and
newline character.
• Syntax:
char c=cin.get();
Example
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
void put()
• It is a method of cout object and it is used to
print the specified character on the screen or
monitor.
• Syntax:
cout.put(variable / character);
Example
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
getline(char ,int size)
• This is a method of cin object and it is used to
input a string with multiple spaces.
• Syntax:
char x[30];
cin.getline(x,30);
Example
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as
input
cout<<c<<endl;
return 0;
}
write(char , int n)
• It is a method of cout object. This method is
used to write n character from buffer variable.
• Syntax:
cout.write(x,2);
Example
#include<iostream>
using namespace std;
int main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;
return 0;
}
cin
• It is the method to take input any variable /
character / string.
• Syntax:
cin>>variable / character / String / ;
Example
#include<iostream>
using namespace std;
int main()
{
int num;
char ch;
string str;
cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;
return 0;
}
cout
• This method is used to print variable / string /
character.
Syntax:
cout<< variable / charcter / string;
Example
#include<iostream>
using namespace std;
int main()
{
int num=100;
char ch='X';
string str="Deepak";
cout<<"Number is "<<num<<endl; //Prints value of variable;
cout<<"Character is "<<ch<<endl; //Prints character;
cout<<"String is "<<str<<endl; //Prints string;
return 0;
}
Formatted console input output operations
• In formatted console input output operations we
uses functions to make output in perfect
alignment.
• C++ provides many function to convert any file
into perfect aligned format.
• These functions are available in header
file <iomanip>.
• iomanip refers input output manipulations.
width(n)
• This function is used to set width of the
output.
• Syntax:
cout<<setw(int n);
Example
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x=10;
cout<<setw(20)<<x;
return 0;
}
fill(char)
• This function is used to fill specified character
at unused space.
• Syntax:
cout<<setfill('character')<<variable;
Example
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
return 0;
}
precison(n)
• This method is used for setting floating point
of the output.
• Syntax:
cout<<setprecision('int n')<<variable;
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}
Working with Files
• The data are stored in the secondary device
using the concept of files.
• Files are the collection of related data stored
in a particular area on the disk.
• Programs can be written to perform read and
write operations on these files.
Working with files generally requires the
following kinds of data communication
methodologies:
• Data transfer between console units.
• Data transfer between the program and the
disk file.
• We use the header file <fstream>
File Handling Classes
• ofstream: It represents output Stream and this is
used for writing in files.
• ifstream: It represents input Stream and this is
used for reading from files.
• fstream: It represents both output Stream and
input Stream. So it can read from files and write
to files.
Operations in File Handling
• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()
Opening & Closing a file in C++
Opening a file
Files can be opened in two ways. They are:
• Using constructor function of the class.
- Useful when we use only one file.
• Using member function open of the class.
- Manage multiple files using one stream.
Using constructor function of the class
The syntax of opening a file in C++ is:
open (filename, mode);
There are some mode flags used for file opening. These are:
• ios::app: append mode
• ios::ate: open a file in this mode for read/write controlling to
the end of the file
• ios::in: open file in this mode for reading
• ios::out: open file in this mode for writing
• ios::trunk: when any file already exists, its contents will be
truncated before file opening
• When any C++ program terminates, it
automatically flushes out all the streams,
releases all the allocated memory and closes
all the opened files.
• But it is good to use the close() function to
close the file related streams and it is a
member of ifsream, ofstream and fstream
objects.
• The structure of using this function is:
void close();
Reading from and writing to file
• While doing C++ program, programmers write
information to a file from the program using the
stream insertion operator (<<) and reads
information using the stream extraction
operator (>>).
• The only difference is that for files programmers
need to use an ofstream or fstream object
instead of the cout object and ifstream or
fstream object instead of the cin object.
Opening file using constructor
• This involves the following steps:-
i) Create a file stream object to manage the
stream using the appropriate class.
ii) Initialize the file object with desired
filename.
ofstream outfile(“result”);
outfile<<<“total”;
ifstream infile(“data”);
infile>>number;
Working with Single file
#include<fstream.h>
void main()
{
ofstream outf(“item”);
cout<<“enter name”;
char name[30];
cin>>name;
outf<<name;
float cost;
cin>>cost;
outf<<cost;
outf.close();
ifstream inf(“item”);
inf>>name;
inf>>cost;
cout<<name;
cout<<cost;
inf.close();
}
• When a file is opened for writing only, a new
file is created if there is no file of that name.
• If file by that name exists already, then its
contents are deleted and file is presented as a
clean file.
• Without losing the original contents, open an
existing file for updating.
Opening file using open() function
• Function open() can be used open multiple files
that uses the same stream object.
fstream stream_obj;
stream_obj.open(“file_name”);
• First file is closed before opening the second one.
This is necessary because stream can be
connected to only one file at a time.
Example
ofstream outfile;
outfile.open(“data1”);
--------------
---------------
outfile.close();
outfile.open(“data2”);
--------------
---------------
outfile.close();
Create file with Open() function
#include<fstream.h>
void main()
{
ofstream fout;
fout.open(“counting”);
fout<<“US”;
fout<<“UK”;
fout<<“india”;
fout.close();
fout.open(“capital”);
fout<<“washington”;
fout<<“london”;
fout<<“delhi”;
fout.close();
• //reading the files(PTO)
int N=80;
char line[N];
ifstream fin;
fin.open(“country”);
while(fin)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
fin.open(“capital”);
while(fin)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
}
Detecting end-of-file
• While(fin) //ifstream object
• Another method:
• if(fin.eof()!=0);
• Eof() is a member of ios class.
• This statement terminates the program on
reaching the end of file.
More about open file modes
• object.open(“filename”); ///one argument
• open() can take 2 arguments.
object.open(“filename”,mode);
• Member function contain default values for
second argument and therefore they use
default values in the absence of actual values.
• Ios::in
• Ios::out

More Related Content

Similar to 13 file handling in C++.pptx oops object oriented programming (20)

File handling in c++
File handling in c++File handling in c++
File handling in c++
Daniel Nyagechi
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Working with files in c++. file handling
Working with files in c++. file handlingWorking with files in c++. file handling
Working with files in c++. file handling
tfluid16
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
radhushri
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
Files in c++
Files in c++Files in c++
Files in c++
NivethaJeyaraman
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Streams and Files
Streams and FilesStreams and Files
Streams and Files
Munazza-Mah-Jabeen
 
Introduction-to-Streams-and-Files-in-C.pptx
Introduction-to-Streams-and-Files-in-C.pptxIntroduction-to-Streams-and-Files-in-C.pptx
Introduction-to-Streams-and-Files-in-C.pptx
mubarrahnaeem12
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
Ananda Kumar HN
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
file.pptx 43dcsddsafgdewdvvbghghsdwweffrfile.pptx 43dcsddsafgdewdvvbghghsdwweffr
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
abdelhamidatef1
 
Data file handling
Data file handlingData file handling
Data file handling
TAlha MAlik
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Working with files in c++. file handling
Working with files in c++. file handlingWorking with files in c++. file handling
Working with files in c++. file handling
tfluid16
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
radhushri
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
Introduction-to-Streams-and-Files-in-C.pptx
Introduction-to-Streams-and-Files-in-C.pptxIntroduction-to-Streams-and-Files-in-C.pptx
Introduction-to-Streams-and-Files-in-C.pptx
mubarrahnaeem12
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
Ananda Kumar HN
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
file.pptx 43dcsddsafgdewdvvbghghsdwweffrfile.pptx 43dcsddsafgdewdvvbghghsdwweffr
file.pptx 43dcsddsafgdewdvvbghghsdwweffr
abdelhamidatef1
 
Data file handling
Data file handlingData file handling
Data file handling
TAlha MAlik
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 

Recently uploaded (20)

Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Ad

13 file handling in C++.pptx oops object oriented programming

  • 2. C++ Stream Classes • Stream and stream classes : to implement I/O operations with the console and disk files. • It is a sequence of bytes(or interface).. • It acts as a source from which input data can be obtained. • or as destination to which the output can be sent. • Source stream is called Input stream. • Destination stream is called Output stream.
  • 3. • Data in the Input stream can come from Keyboard etc. • Similarly, data in the output stream can go to the screen. • C++ provides standard iostream library to operate with streams. • Cin and cout are the predefined streams .
  • 4. • If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation . • and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.
  • 5. • istream is a general purpose input stream. cin is an example of an istream. • ostream is a general purpose output stream. cout is the example of ostream. • ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. • ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.
  • 6. • C++ provides the following classes to perform output and input of characters to/from files: 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.
  • 7. Console I/O operations There are mainly two types of console I/O operations form: • Unformatted console input output • Formatted console input output
  • 8. Unformatted input output operations The following are operations of unformatted input / output operations: A) void get() • It is a method of cin object used to input a single character from keyboard. But its main property is that it allows wide spaces and newline character. • Syntax: char c=cin.get();
  • 9. Example #include<iostream> using namespace std; int main() { char c=cin.get(); cout<<c<<endl; return 0; }
  • 10. void put() • It is a method of cout object and it is used to print the specified character on the screen or monitor. • Syntax: cout.put(variable / character);
  • 11. Example #include<iostream> using namespace std; int main() { char c=cin.get(); cout.put(c); //Here it prints the value of variable c; cout.put('c'); //Here it prints the character 'c'; return 0; }
  • 12. getline(char ,int size) • This is a method of cin object and it is used to input a string with multiple spaces. • Syntax: char x[30]; cin.getline(x,30);
  • 13. Example #include<iostream> using namespace std; int main() { cout<<"Enter name :"; char c[10]; cin.getline(c,10); //It takes 10 charcters as input cout<<c<<endl; return 0; }
  • 14. write(char , int n) • It is a method of cout object. This method is used to write n character from buffer variable. • Syntax: cout.write(x,2);
  • 15. Example #include<iostream> using namespace std; int main() { cout<<"Enter name : "; char c[10]; cin.getline(c,10); //It takes 10 charcters as input; cout.write(c,9); //It reads only 9 character from buffer c; return 0; }
  • 16. cin • It is the method to take input any variable / character / string. • Syntax: cin>>variable / character / String / ;
  • 17. Example #include<iostream> using namespace std; int main() { int num; char ch; string str; cout<<"Enter Number"<<endl; cin>>num; //Inputs a variable; cout<<"Enter Character"<<endl; cin>>ch; //Inputs a character; cout<<"Enter String"<<endl; cin>>str; //Inputs a string; return 0; }
  • 18. cout • This method is used to print variable / string / character. Syntax: cout<< variable / charcter / string;
  • 19. Example #include<iostream> using namespace std; int main() { int num=100; char ch='X'; string str="Deepak"; cout<<"Number is "<<num<<endl; //Prints value of variable; cout<<"Character is "<<ch<<endl; //Prints character; cout<<"String is "<<str<<endl; //Prints string; return 0; }
  • 20. Formatted console input output operations
  • 21. • In formatted console input output operations we uses functions to make output in perfect alignment. • C++ provides many function to convert any file into perfect aligned format. • These functions are available in header file <iomanip>. • iomanip refers input output manipulations.
  • 22. width(n) • This function is used to set width of the output. • Syntax: cout<<setw(int n);
  • 23. Example #include<iostream> #include<iomanip> using namespace std; int main() { int x=10; cout<<setw(20)<<x; return 0; }
  • 24. fill(char) • This function is used to fill specified character at unused space. • Syntax: cout<<setfill('character')<<variable;
  • 25. Example #include<iostream> #include<iomanip> using namespace std; int main() { int x=10; cout<<setw(20); cout<<setfill('#')<<x; return 0; }
  • 26. precison(n) • This method is used for setting floating point of the output. • Syntax: cout<<setprecision('int n')<<variable;
  • 27. #include<iostream> #include<iomanip> using namespace std; int main() { float x=10.12345; cout<<setprecision(5)<<x; return 0; }
  • 28. Working with Files • The data are stored in the secondary device using the concept of files. • Files are the collection of related data stored in a particular area on the disk. • Programs can be written to perform read and write operations on these files.
  • 29. Working with files generally requires the following kinds of data communication methodologies: • Data transfer between console units. • Data transfer between the program and the disk file. • We use the header file <fstream>
  • 30. File Handling Classes • ofstream: It represents output Stream and this is used for writing in files. • ifstream: It represents input Stream and this is used for reading from files. • fstream: It represents both output Stream and input Stream. So it can read from files and write to files.
  • 31. Operations in File Handling • Creating a file: open() • Reading data: read() • Writing new data: write() • Closing a file: close()
  • 32. Opening & Closing a file in C++
  • 33. Opening a file Files can be opened in two ways. They are: • Using constructor function of the class. - Useful when we use only one file. • Using member function open of the class. - Manage multiple files using one stream.
  • 34. Using constructor function of the class The syntax of opening a file in C++ is: open (filename, mode); There are some mode flags used for file opening. These are: • ios::app: append mode • ios::ate: open a file in this mode for read/write controlling to the end of the file • ios::in: open file in this mode for reading • ios::out: open file in this mode for writing • ios::trunk: when any file already exists, its contents will be truncated before file opening
  • 35. • When any C++ program terminates, it automatically flushes out all the streams, releases all the allocated memory and closes all the opened files. • But it is good to use the close() function to close the file related streams and it is a member of ifsream, ofstream and fstream objects. • The structure of using this function is: void close();
  • 36. Reading from and writing to file • While doing C++ program, programmers write information to a file from the program using the stream insertion operator (<<) and reads information using the stream extraction operator (>>). • The only difference is that for files programmers need to use an ofstream or fstream object instead of the cout object and ifstream or fstream object instead of the cin object.
  • 37. Opening file using constructor • This involves the following steps:- i) Create a file stream object to manage the stream using the appropriate class. ii) Initialize the file object with desired filename. ofstream outfile(“result”); outfile<<<“total”; ifstream infile(“data”); infile>>number;
  • 38. Working with Single file #include<fstream.h> void main() { ofstream outf(“item”); cout<<“enter name”; char name[30]; cin>>name; outf<<name; float cost; cin>>cost; outf<<cost; outf.close(); ifstream inf(“item”); inf>>name; inf>>cost; cout<<name; cout<<cost; inf.close(); }
  • 39. • When a file is opened for writing only, a new file is created if there is no file of that name. • If file by that name exists already, then its contents are deleted and file is presented as a clean file. • Without losing the original contents, open an existing file for updating.
  • 40. Opening file using open() function • Function open() can be used open multiple files that uses the same stream object. fstream stream_obj; stream_obj.open(“file_name”); • First file is closed before opening the second one. This is necessary because stream can be connected to only one file at a time.
  • 42. Create file with Open() function #include<fstream.h> void main() { ofstream fout; fout.open(“counting”); fout<<“US”; fout<<“UK”; fout<<“india”; fout.close(); fout.open(“capital”); fout<<“washington”; fout<<“london”; fout<<“delhi”; fout.close(); • //reading the files(PTO)
  • 43. int N=80; char line[N]; ifstream fin; fin.open(“country”); while(fin) { fin.getline(line,N); cout<<line; } fin.close(); fin.open(“capital”); while(fin) { fin.getline(line,N); cout<<line; } fin.close(); }
  • 44. Detecting end-of-file • While(fin) //ifstream object • Another method: • if(fin.eof()!=0); • Eof() is a member of ios class. • This statement terminates the program on reaching the end of file.
  • 45. More about open file modes • object.open(“filename”); ///one argument • open() can take 2 arguments. object.open(“filename”,mode); • Member function contain default values for second argument and therefore they use default values in the absence of actual values. • Ios::in • Ios::out