SlideShare una empresa de Scribd logo
1 de 21
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.

Más contenido relacionado

La actualidad más candente

Data file handling
Data file handlingData file handling
Data file handling
TAlha MAlik
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
(Julien le dem) parquet
(Julien le dem)   parquet(Julien le dem)   parquet
(Julien le dem) parquet
NAVER D2
 
Csc1100 lecture15 ch09
Csc1100 lecture15 ch09Csc1100 lecture15 ch09
Csc1100 lecture15 ch09
IIUM
 

La actualidad más candente (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 a CPP17 - File IO

FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 

Similar a 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
 
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]
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 

Más de Michael Heron

Más de 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
 

Último

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Último (20)

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

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.