SlideShare una empresa de Scribd logo
1 de 21
Filing in C++
Lecture # 14
Stream Classes
 A stream

is a general name given to a flow

of data.
 A stream is represented by an object of a
particular class.
 Example: cin and cout stream objects.
 Different streams are used to represent
different kinds of data flow.
 Example: ifstream class represent data
flow from input disk files.
The Stream Class Hierarchy
ios
istream
ifstream

ostream
iostream
fstream

ofstream
Formatted File I/O
 In formatted I/O, numbers are stored on

disk as a series of characters.
 This can be inefficient for numbers with
many digits.
 However, it is easy to implement.
 Characters and strings are stored more or
less normally.
Formatted File I/O
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
char ch='x';
int j = 77;
double d = 6.02;
string str1 = "kafka";
string str2 = "proust";

ofstream outfile("fdata.txt");
outfile << ch
<< j
<< ' '
<< d
<< str1
<< ' '
<< str2;
cout<<"file written"<<endl;
return 0;
}
Formatted File I/O








We created an object of ofstream and initialized
it to the file FDATA.TXT.
This initialization sets aside various resources
for the file, and accesses or opens the file of that
name on the disk.
If the file does not exist, it is created.
If it does exist, it is truncated and the new data
replaces the old.
The outfile object acts much as cout object.
So we can use the insertion operator (<<) to
output variables of any basic type to the file.
Formatted File I/O







When the program terminates, the outfile object goes out
of scope. This calls its destructor, which closes the file,
so we don’t need to close the file explicitly.
We must separate numbers with nonnumeric characters.
Strings must be separated with white spaces.
This implies that strings cannot contain imbedded
blanks.
Characters need no delimiters, since they have a fixed
length.
Formatted File I/O
int main()
{
char ch;
int j;
double d;
string str1;
string str2;
ifstream infile("fdata.txt");

infile >> ch
>> j
>> d
>> str1
>> str2;
cout<<ch<<endl
<<j<<endl
<<d<<endl
<<str1<<endl
<<str2<<endl;
return 0;
}
Strings with Embedded Blanks




To handle strings with embedded blanks, we need to
write a specific delimiter character after each string, and
use the getline() function, rather than the extraction
operator, to read them in.
This function reads characters, including white-space,
until it encounters the ‘n’ character, and places the
resulting string in the buffer supplied as an argument.
The maximum size of the buffer is given as the second
argument.
Strings with Embedded Blanks
int main()
{
ofstream outfile("test.txt");
outfile<< "I fear thee, ancient Mariner!n";
outfile<< "I fear thy skinny handn";
return 0;
}
Strings with Embedded Blanks
int main()
{
const int MAX=80;
char buffer[MAX];
ifstream infile("test.txt");
while(!infile.eof())
{
infile.getline(buffer,MAX);
cout<<buffer<<endl;
}
return 0;
}
Binary I/O







When storing large amount of data, it is more efficient to
use binary I/O.
In binary I/O, numbers are stored as they are in the
computer’s RAM memory, rather than as strings of
characters.
write(), a member of ofstream, and read(), a member of
ifstream are used.
These functions think about data in terms of bytes (type
char).
They don’t care how the data is formatted, they simply
transfer a buffer full of bytes from and to a disk file.
Binary I/O
 The parameters to write() and read() are

the address of the data buffer and its
length.
 The address must be cast, using
reinterpret_cast, to type char*, and the
length is the length in bytes (characters),
not the number of data items in the buffer.
Binary I/O
int main()
{
const int MAX=100;
int j;
int buff[MAX];
for(j=0; j<MAX; j++)
buff[j]=j;
ofstream os("test.dat",
ios::binary);
os.write(reinterpret_cast<cha
r*>(buff), MAX*sizeof(int));
os.close();
for(j=0; j<MAX; j++)
buff[j]=0;

ifstream is("test.dat",
ios::binary);
is.read(reinterpret_cast<char*
>(buff), MAX*sizeof(int));
for(j=0; j<MAX; j++){
if(buff[j]!=j)
{cerr<<"data is
incorrect"<<endl;}
}
cout<<"data is correct"<<endl;
return 0;
}
Binary I/O








We must use the ios::binary argument in the
second parameter to constructor when working
with binary data.
We need to use the reinterpret_cast operation to
make it possible for a buffer of type int to look to
the read() and write() functions like a buffer of
type char.
The reinterpret_cast operator is how we tell the
compiler. “I know you won’t like this, but I want
to do it anyway.”
It changes a section of memory without caring if
it makes sense.
Object I/O
 We can also write objects, of user defined

classes, to files.
 Similarly, we can read objects from files.
 When writing an object we generally want
to use binary mode.




This writes the same bit configuration to disk
that was stored in memory
and ensures that numerical data contained in
objects is handled properly.
Example: Object I/O
#include<iostream>
using namespace std;
class Person
{
private:
char name[40];
int age;
public:
void readData()
{
cout<<"Enter name: ";

cin>>name;
cout<<"Enter age: ";
cin>>age;
}
void showData()
{
cout<<name<<endl
<<age<<endl;
}
};
Example: Object I/O
#include"person.h"
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
Person p;
p.readData();
ofstream os("person.dat",
ios::binary);

os.write(reinterpret_cast<char*
>(&p), sizeof(Person));
os.close();
Person p1;
ifstream is("person.dat",
ios::binary);
is.read(reinterpret_cast<char*>(
&p1), sizeof(Person));
p1.showData();
return 0;
}
I/O with Multiple Objects
int main() {
char ch;
Person p;
fstream file;
file.open("group.dat",ios::app | ios::out | ios::in | ios::binary);
do {
p.readData();
file.write(reinterpret_cast<char*>(&p), sizeof(Person));
cout<<"Enter another person(y/n)? : "<<endl;
cin>>ch;
}while(ch=='y');
I/O with Multiple Objects
file.seekg(0);//reset to start of file
file.read(reinterpret_cast<char*>(&p), sizeof(Person));
while(!file.eof())
{
cout<<"nPerson: ";
p.showData();
file.read(reinterpret_cast<char*>(&p), sizeof(Person));
}
return 0;
}
I/O with Multiple Objects
 If we want to create a file stream object

that can be used for both, reading to and
writing from a file, we need to create an
object of fstream class.
 open() function is a member of the
fstream class.
 We can create a stream object once, and
can open it repeatedly.

Más contenido relacionado

La actualidad más candente

Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operationsarchikabhatia
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in CAbinaya B
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Deepak Singh
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&aKumaran K
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc csKALAISELVI P
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++Fahim Adil
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programmingIcaii Infotech
 

La actualidad más candente (20)

Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Managing I/O & String function in C
Managing I/O & String function in CManaging I/O & String function in C
Managing I/O & String function in C
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Strings
StringsStrings
Strings
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Strings in C
Strings in CStrings in C
Strings in C
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
String.ppt
String.pptString.ppt
String.ppt
 
Iostream in c++
Iostream in c++Iostream in c++
Iostream in c++
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
 
strings
stringsstrings
strings
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 

Destacado

Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Abdullah khawar
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingRai University
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++harman kaur
 

Destacado (6)

Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++
 

Similar a Ds lec 14 filing in c++

streams and files
 streams and files streams and files
streams and filesMariam Butt
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programmingnmahi96
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string libraryMomenMostafa
 
C programming session 01
C programming session 01C programming session 01
C programming session 01Dushmanta Nath
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)Saifur Rahman
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with filesramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with fileskirupasuchi1996
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docxAbdulrahman890100
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptxradhushri
 

Similar a Ds lec 14 filing in c++ (20)

File handling in c++
File handling in c++File handling in c++
File handling in c++
 
streams and files
 streams and files streams and files
streams and files
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Cpprm
CpprmCpprm
Cpprm
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
7512635.ppt
7512635.ppt7512635.ppt
7512635.ppt
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
 

Último

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Ds lec 14 filing in c++

  • 2. Stream Classes  A stream is a general name given to a flow of data.  A stream is represented by an object of a particular class.  Example: cin and cout stream objects.  Different streams are used to represent different kinds of data flow.  Example: ifstream class represent data flow from input disk files.
  • 3. The Stream Class Hierarchy ios istream ifstream ostream iostream fstream ofstream
  • 4. Formatted File I/O  In formatted I/O, numbers are stored on disk as a series of characters.  This can be inefficient for numbers with many digits.  However, it is easy to implement.  Characters and strings are stored more or less normally.
  • 5. Formatted File I/O #include<iostream> #include<fstream> #include<string> using namespace std; int main() { char ch='x'; int j = 77; double d = 6.02; string str1 = "kafka"; string str2 = "proust"; ofstream outfile("fdata.txt"); outfile << ch << j << ' ' << d << str1 << ' ' << str2; cout<<"file written"<<endl; return 0; }
  • 6. Formatted File I/O       We created an object of ofstream and initialized it to the file FDATA.TXT. This initialization sets aside various resources for the file, and accesses or opens the file of that name on the disk. If the file does not exist, it is created. If it does exist, it is truncated and the new data replaces the old. The outfile object acts much as cout object. So we can use the insertion operator (<<) to output variables of any basic type to the file.
  • 7. Formatted File I/O      When the program terminates, the outfile object goes out of scope. This calls its destructor, which closes the file, so we don’t need to close the file explicitly. We must separate numbers with nonnumeric characters. Strings must be separated with white spaces. This implies that strings cannot contain imbedded blanks. Characters need no delimiters, since they have a fixed length.
  • 8. Formatted File I/O int main() { char ch; int j; double d; string str1; string str2; ifstream infile("fdata.txt"); infile >> ch >> j >> d >> str1 >> str2; cout<<ch<<endl <<j<<endl <<d<<endl <<str1<<endl <<str2<<endl; return 0; }
  • 9. Strings with Embedded Blanks   To handle strings with embedded blanks, we need to write a specific delimiter character after each string, and use the getline() function, rather than the extraction operator, to read them in. This function reads characters, including white-space, until it encounters the ‘n’ character, and places the resulting string in the buffer supplied as an argument. The maximum size of the buffer is given as the second argument.
  • 10. Strings with Embedded Blanks int main() { ofstream outfile("test.txt"); outfile<< "I fear thee, ancient Mariner!n"; outfile<< "I fear thy skinny handn"; return 0; }
  • 11. Strings with Embedded Blanks int main() { const int MAX=80; char buffer[MAX]; ifstream infile("test.txt"); while(!infile.eof()) { infile.getline(buffer,MAX); cout<<buffer<<endl; } return 0; }
  • 12. Binary I/O      When storing large amount of data, it is more efficient to use binary I/O. In binary I/O, numbers are stored as they are in the computer’s RAM memory, rather than as strings of characters. write(), a member of ofstream, and read(), a member of ifstream are used. These functions think about data in terms of bytes (type char). They don’t care how the data is formatted, they simply transfer a buffer full of bytes from and to a disk file.
  • 13. Binary I/O  The parameters to write() and read() are the address of the data buffer and its length.  The address must be cast, using reinterpret_cast, to type char*, and the length is the length in bytes (characters), not the number of data items in the buffer.
  • 14. Binary I/O int main() { const int MAX=100; int j; int buff[MAX]; for(j=0; j<MAX; j++) buff[j]=j; ofstream os("test.dat", ios::binary); os.write(reinterpret_cast<cha r*>(buff), MAX*sizeof(int)); os.close(); for(j=0; j<MAX; j++) buff[j]=0; ifstream is("test.dat", ios::binary); is.read(reinterpret_cast<char* >(buff), MAX*sizeof(int)); for(j=0; j<MAX; j++){ if(buff[j]!=j) {cerr<<"data is incorrect"<<endl;} } cout<<"data is correct"<<endl; return 0; }
  • 15. Binary I/O     We must use the ios::binary argument in the second parameter to constructor when working with binary data. We need to use the reinterpret_cast operation to make it possible for a buffer of type int to look to the read() and write() functions like a buffer of type char. The reinterpret_cast operator is how we tell the compiler. “I know you won’t like this, but I want to do it anyway.” It changes a section of memory without caring if it makes sense.
  • 16. Object I/O  We can also write objects, of user defined classes, to files.  Similarly, we can read objects from files.  When writing an object we generally want to use binary mode.   This writes the same bit configuration to disk that was stored in memory and ensures that numerical data contained in objects is handled properly.
  • 17. Example: Object I/O #include<iostream> using namespace std; class Person { private: char name[40]; int age; public: void readData() { cout<<"Enter name: "; cin>>name; cout<<"Enter age: "; cin>>age; } void showData() { cout<<name<<endl <<age<<endl; } };
  • 18. Example: Object I/O #include"person.h" #include<iostream> #include<fstream> #include<string> using namespace std; int main() { Person p; p.readData(); ofstream os("person.dat", ios::binary); os.write(reinterpret_cast<char* >(&p), sizeof(Person)); os.close(); Person p1; ifstream is("person.dat", ios::binary); is.read(reinterpret_cast<char*>( &p1), sizeof(Person)); p1.showData(); return 0; }
  • 19. I/O with Multiple Objects int main() { char ch; Person p; fstream file; file.open("group.dat",ios::app | ios::out | ios::in | ios::binary); do { p.readData(); file.write(reinterpret_cast<char*>(&p), sizeof(Person)); cout<<"Enter another person(y/n)? : "<<endl; cin>>ch; }while(ch=='y');
  • 20. I/O with Multiple Objects file.seekg(0);//reset to start of file file.read(reinterpret_cast<char*>(&p), sizeof(Person)); while(!file.eof()) { cout<<"nPerson: "; p.showData(); file.read(reinterpret_cast<char*>(&p), sizeof(Person)); } return 0; }
  • 21. I/O with Multiple Objects  If we want to create a file stream object that can be used for both, reading to and writing from a file, we need to create an object of fstream class.  open() function is a member of the fstream class.  We can create a stream object once, and can open it repeatedly.