SlideShare a Scribd company logo
File I/O
Michael Heron
Introduction
• File I/O in C++ is a relatively straightforward affair.
• For the most part.
• Almost all I/O in C++ is handled via streams.
• Like cin and cout
• Random access files also supported.
• Not our focus.
• Concept complicated slightly by the presence of objects.
• Require a strategy to deal with object representation.
Stream I/O
• Stream I/O is the simplest kind of I/O
• Read in sequences of bytes from a device.
• Write out sequences of bytes to a device
• Broken into two broad categories.
• Low level I/O, whereby a set number of bytes are transferred.
• No representation of underlying data formats
• High level I/O
• Bytes are grouped into meaningful units
• Such as ints, chars or strings
Random Access Files
• Sequential files must be read in order.
• Random access files permit non-sequential access to data.
• System is considerably more complicated.
• Must have a firm definition of all data attributes.
• Issue complicated by the presence of ‘non-fixed length’ data
structures.
• Such as strings.
• Must work out the size of a record on disk.
Basic File I/O - Output
• Straightforward process
• #include <fstream>
• Instantiate an ofstream object
• Use it like cout
• Close in when done:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("blah.txt");
out << "Hello World" << endl;
out.close
return 0;
}
Basic File I/O - Input
• Same deal
• Use a ifstream object
• Use it like cin
• Close when done
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("blah.txt");
string bleh;
in >> bleh;
cout << bleh;
in.close();
return 0;
}
The Process
• A file in C++ has two names.
• The name it has in the directory structure.
• Such as c:/bing.txt
• The name it has in the object you create in your C++ program.
• The link between the two is forged by the creation of a stream
object.
• This creates the connection between the two.
The Process
• We must close files when we are finished with them.
• Signifies to the O/S that we are done with the file.
• Flushes all remaining file accesses and commits them to the file.
• Releases the resources in our system.
• We need to do this regardless of whether it is an input or an
output operation.
Stream Objects
• The constructor for a stream object can take a second
parameter.
• The type of mode for the I/O
• These are defined in the namespace ios:
• ofstream out ("blah.txt", ios::app);
• Used for specialising the type of stream.
• Above sets an append.
• Others have more esoteric use.
So Far, So Good…
• Limited opportunities for expression with this system.
• Need more precision on representation of data
• There exist a range of stream manipulators that allow for fine-
grained control over stream I/O
• dec
• hex
• octal
• setbase
Stream Manipulators
• These work on simple screen/keyboard I/O and file I/O
• They make use of the Power of Polymorphism
• They are defined in the std namespace.
• Inserted into the stream where needed. Acts on the stream from
that point onwards.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
cout << oct << 10;
return 0;
}
Stream Manipulators
• Some stream manipulators are parameterized
• Like setbase
• These are called parameterized stream manipulators
• They get defined in iomanip.h
• When used, they must be provided with the parameter that
specialises their behaviour.
• setbase takes one of three parameters
• 10, 8 or 16
Precision
• One of the common things we want to be able to do with
floating point numbers is represent their precision.
• Limit the number of decimal places
• This is done using the precision method and the fixed stream
manipulator.
• Precision takes as its parameter the number of decimal places to
use.
Precision
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.14159265;
cout.precision (5);
cout << fixed << pi;
return 0;
}
Width
• We can use the width method to set the maximum field width
of data.
• This is not a sticky modifier
• Impacts on the next insertion or extraction only.
• It does not truncate data
• You get the full number.
• It does pad data
• Useful for strings.
• Defaults to a blank space. Can use the setfill modifier to change the
padding character.
Other Stream Manipulators
• showpoint
• Shows all the trailing zeroes in a floating point number.
• Switched off with noshowpoint
• Justification
• Used the parameterized setw to set the width of the of the value
• Use left or right to justify
• Default is right jutsification
• Research these
• Quite a lot to handle various purposes.
Reading In A Paragraph
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
ifstream in ("blah.txt");
string str;
in >> str;
while (!in.eof()) {
cout << str << " ";
in >> str;
}
return 0;
}
Buffering
• The files that exist on the disk do not necessarily reflect the
information we have told C++ to write.
• Why?
• The answer is down to buffering.
• File IO is one of the most expensive procedures in executing a
program.
• C++ will try to keep the I/O costs down as far as possible through
buffering.
What’s In A File Access?
• File Accessing is broken down into two main stages.
• Seeking the file
• Interacting with the file.
• Imagine 500 instructions to write to a file.
• 500 seeks, 500 writes
• Buffering maintains an internal memory cache of write
accesses.
• Reduce down to 1 seek.
Buffering
• The file is updated under the following circumstances:
• When the file is closed.
• Thus, one of the reasons why we must close our files.
• When the buffer is full.
• Buffers are limited in size, and are ‘flushed’ when that size is
reached.
• When you explicitly instruct it.
• Done sometimes with manipulators (such as endl)
• Done using the sync method of the stream.
Summary
• File I/O in C++ is handled in the same way as
keyboard/monitor I/O
• At least as far as stream-based IO is concerned.
• Stream I/O is very versatile in C++
• Handled through stream manipulators
• File accesses in C++ are, as far as is possible, buffered.
• This greatly reduces the load on the hardware.

More Related Content

What's hot

08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
Haresh Jaiswal
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
File Pointers
File PointersFile Pointers
Data file handling
Data file handlingData file handling
Data file handling
TAlha MAlik
 
File handling
File handlingFile handling
File handling
muhammad sharif bugti
 
Comp102 lec 11
Comp102   lec 11Comp102   lec 11
Comp102 lec 11
Fraz Bakhsh
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
Io stream
Io streamIo stream
Io stream
Parthipan Parthi
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
Deepak Hagadur Bheemaraju
 
Lzw compression
Lzw compressionLzw compression
Lzw compression
Meghna Singh
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
Ghadeer AlHasan
 
05io
05io05io
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
Filehandling
FilehandlingFilehandling
Filehandling
Amandeep Kaur
 
(Julien le dem) parquet
(Julien le dem)   parquet(Julien le dem)   parquet
(Julien le dem) parquet
NAVER D2
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
Ravi Kiran Khareedi
 
Csc1100 lecture15 ch09
Csc1100 lecture15 ch09Csc1100 lecture15 ch09
Csc1100 lecture15 ch09
IIUM
 

What's hot (20)

08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
File Pointers
File PointersFile Pointers
File Pointers
 
Data file handling
Data file handlingData file handling
Data file handling
 
File handling
File handlingFile handling
File handling
 
Comp102 lec 11
Comp102   lec 11Comp102   lec 11
Comp102 lec 11
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
14 file handling
14 file handling14 file handling
14 file handling
 
Io stream
Io streamIo stream
Io stream
 
working with files
working with filesworking with files
working with files
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 
Lzw compression
Lzw compressionLzw compression
Lzw compression
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
 
05io
05io05io
05io
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Filehandling
FilehandlingFilehandling
Filehandling
 
(Julien le dem) parquet
(Julien le dem)   parquet(Julien le dem)   parquet
(Julien le dem) parquet
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
 
Csc1100 lecture15 ch09
Csc1100 lecture15 ch09Csc1100 lecture15 ch09
Csc1100 lecture15 ch09
 

Similar to CPP17 - File IO

Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
YourHelper1
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
null.pptx
null.pptxnull.pptx
null.pptx
AnshKarwa
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
GOKULKANNANMMECLECTC
 
Intro To C++ - Class #21: Files
Intro To C++ - Class #21: FilesIntro To C++ - Class #21: Files
Intro To C++ - Class #21: Files
Blue Elephant Consulting
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
pinuadarsh04
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
Abdullah Jan
 
INT 222.pptx
INT 222.pptxINT 222.pptx
INT 222.pptx
Saunya2
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
31cs
31cs31cs
31cs
Sireesh K
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
Khushal Mehta
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
SURBHI SAROHA
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
32sql server
32sql server32sql server
32sql server
Sireesh K
 
Yihan Lian & Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
Yihan Lian &  Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]Yihan Lian &  Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
Yihan Lian & Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
RootedCON
 

Similar to CPP17 - File IO (20)

Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
null.pptx
null.pptxnull.pptx
null.pptx
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
 
Intro To C++ - Class #21: Files
Intro To C++ - Class #21: FilesIntro To C++ - Class #21: Files
Intro To C++ - Class #21: Files
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
INT 222.pptx
INT 222.pptxINT 222.pptx
INT 222.pptx
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
31cs
31cs31cs
31cs
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
32sql server
32sql server32sql server
32sql server
 
Yihan Lian & Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
Yihan Lian &  Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]Yihan Lian &  Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
Yihan Lian & Zhibin Hu - Smarter Peach: Add Eyes to Peach Fuzzer [rooted2017]
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Recently uploaded

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 

CPP17 - File IO

  • 2. Introduction • File I/O in C++ is a relatively straightforward affair. • For the most part. • Almost all I/O in C++ is handled via streams. • Like cin and cout • Random access files also supported. • Not our focus. • Concept complicated slightly by the presence of objects. • Require a strategy to deal with object representation.
  • 3. Stream I/O • Stream I/O is the simplest kind of I/O • Read in sequences of bytes from a device. • Write out sequences of bytes to a device • Broken into two broad categories. • Low level I/O, whereby a set number of bytes are transferred. • No representation of underlying data formats • High level I/O • Bytes are grouped into meaningful units • Such as ints, chars or strings
  • 4. Random Access Files • Sequential files must be read in order. • Random access files permit non-sequential access to data. • System is considerably more complicated. • Must have a firm definition of all data attributes. • Issue complicated by the presence of ‘non-fixed length’ data structures. • Such as strings. • Must work out the size of a record on disk.
  • 5. Basic File I/O - Output • Straightforward process • #include <fstream> • Instantiate an ofstream object • Use it like cout • Close in when done: #include <iostream> #include <fstream> using namespace std; int main() { ofstream out("blah.txt"); out << "Hello World" << endl; out.close return 0; }
  • 6. Basic File I/O - Input • Same deal • Use a ifstream object • Use it like cin • Close when done #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream in("blah.txt"); string bleh; in >> bleh; cout << bleh; in.close(); return 0; }
  • 7. The Process • A file in C++ has two names. • The name it has in the directory structure. • Such as c:/bing.txt • The name it has in the object you create in your C++ program. • The link between the two is forged by the creation of a stream object. • This creates the connection between the two.
  • 8. The Process • We must close files when we are finished with them. • Signifies to the O/S that we are done with the file. • Flushes all remaining file accesses and commits them to the file. • Releases the resources in our system. • We need to do this regardless of whether it is an input or an output operation.
  • 9. Stream Objects • The constructor for a stream object can take a second parameter. • The type of mode for the I/O • These are defined in the namespace ios: • ofstream out ("blah.txt", ios::app); • Used for specialising the type of stream. • Above sets an append. • Others have more esoteric use.
  • 10. So Far, So Good… • Limited opportunities for expression with this system. • Need more precision on representation of data • There exist a range of stream manipulators that allow for fine- grained control over stream I/O • dec • hex • octal • setbase
  • 11. Stream Manipulators • These work on simple screen/keyboard I/O and file I/O • They make use of the Power of Polymorphism • They are defined in the std namespace. • Inserted into the stream where needed. Acts on the stream from that point onwards. #include <iostream> #include <fstream> #include <string> using namespace std; int main() { cout << oct << 10; return 0; }
  • 12. Stream Manipulators • Some stream manipulators are parameterized • Like setbase • These are called parameterized stream manipulators • They get defined in iomanip.h • When used, they must be provided with the parameter that specialises their behaviour. • setbase takes one of three parameters • 10, 8 or 16
  • 13. Precision • One of the common things we want to be able to do with floating point numbers is represent their precision. • Limit the number of decimal places • This is done using the precision method and the fixed stream manipulator. • Precision takes as its parameter the number of decimal places to use.
  • 14. Precision #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { float pi = 3.14159265; cout.precision (5); cout << fixed << pi; return 0; }
  • 15. Width • We can use the width method to set the maximum field width of data. • This is not a sticky modifier • Impacts on the next insertion or extraction only. • It does not truncate data • You get the full number. • It does pad data • Useful for strings. • Defaults to a blank space. Can use the setfill modifier to change the padding character.
  • 16. Other Stream Manipulators • showpoint • Shows all the trailing zeroes in a floating point number. • Switched off with noshowpoint • Justification • Used the parameterized setw to set the width of the of the value • Use left or right to justify • Default is right jutsification • Research these • Quite a lot to handle various purposes.
  • 17. Reading In A Paragraph #include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { ifstream in ("blah.txt"); string str; in >> str; while (!in.eof()) { cout << str << " "; in >> str; } return 0; }
  • 18. Buffering • The files that exist on the disk do not necessarily reflect the information we have told C++ to write. • Why? • The answer is down to buffering. • File IO is one of the most expensive procedures in executing a program. • C++ will try to keep the I/O costs down as far as possible through buffering.
  • 19. What’s In A File Access? • File Accessing is broken down into two main stages. • Seeking the file • Interacting with the file. • Imagine 500 instructions to write to a file. • 500 seeks, 500 writes • Buffering maintains an internal memory cache of write accesses. • Reduce down to 1 seek.
  • 20. Buffering • The file is updated under the following circumstances: • When the file is closed. • Thus, one of the reasons why we must close our files. • When the buffer is full. • Buffers are limited in size, and are ‘flushed’ when that size is reached. • When you explicitly instruct it. • Done sometimes with manipulators (such as endl) • Done using the sync method of the stream.
  • 21. Summary • File I/O in C++ is handled in the same way as keyboard/monitor I/O • At least as far as stream-based IO is concerned. • Stream I/O is very versatile in C++ • Handled through stream manipulators • File accesses in C++ are, as far as is possible, buffered. • This greatly reduces the load on the hardware.