SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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++
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
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 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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Kürzlich hochgeladen (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
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 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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

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.