SlideShare a Scribd company logo
1 of 52
A First Book of C++A First Book of C++
Chapter 9Chapter 9
I/O Streams and Data FilesI/O Streams and Data Files
∗ In this chapter, you will learn about:
∗ I/O File Stream Objects and Methods
∗ Reading and Writing Text Files
∗ Random File Access
∗ File Streams as Function Arguments
∗ Common Programming Errors
∗ The iostream Class Library
A First Book of C++ 4th Edition 2
Objectives
∗ To store and retrieve data outside a C++ program, you
need two things:
∗ A file
∗ A file stream object
A First Book of C++ 4th Edition 3
I/O File Stream Objects and Methods
∗ File: collection of data stored together under
common name, usually on disk, USB drive, or CD/DVD
∗ C++ programs stored on disk are examples of files
∗ Stored data in program file is the code that becomes
input data to C++ compiler
∗ A C++ program is not usually considered data file
∗ Data file typically refers only to files containing the
data used in C++ program
A First Book of C++ 4th Edition 4
Files
∗ External name: unique filename for file
∗ External name is how operating system knows file
∗ Contents of directory or folder are listed by external
names
∗ Each computer operating system has its own
specifications for external filename size
∗ Table 9.1 lists specifications for more commonly used
operating systems
A First Book of C++ 4th Edition 5
Files (cont'd.)
A First Book of C++ 4th Edition 6
Files (cont'd.)
∗ Use descriptive names
∗ Avoid long filenames
∗ They take more time to type and can result in typing
errors
∗ Manageable length for filename is 12 to 14 characters,
with maximum of 25 characters
∗ Choose filenames that indicate type of data in file and
application for which it is used
∗ Frequently, first eight characters describe data, and an
extension describes application
A First Book of C++ 4th Edition 7
Files (cont'd.)
∗ Using DOS convention, the following are all valid
computer data filenames:
prices.dat records info.txt
exper1.dat scores.dat math.mem
A First Book of C++ 4th Edition 8
Files (cont'd.)
∗ Two basic types of files: both store data using binary
code
∗ Text (character-based) files: store each character using
individual character code (typically ASCII or Unicode)
∗ Advantage: allows files to be displayed by word-processing
program or text editor
∗ Binary-based files: store numbers in binary form and
strings in ASCII or Unicode form
∗ Advantage: provides compactness
A First Book of C++ 4th Edition 9
Files (cont'd.)
∗ File stream: one-way transmission path used to
connect a file to a program
∗ Mode (of file stream): determines whether path will
move data from file into program or from program to
file
∗ Input file stream: used to transfer data from a file to a
program
∗ Output file stream: sends data from a program to a file
A First Book of C++ 4th Edition 10
File Stream Objects
∗ Direction (mode) of file stream is defined in relation
to program and not file:
∗ Data that goes into program are considered input data
∗ Data sent out from program are considered output data
∗ Figure 9.1 illustrates data flow from and to file using
input and output file streams
A First Book of C++ 4th Edition 11
File Stream Objects (cont'd.)
A First Book of C++ 4th Edition 12
File Stream Objects (cont'd.)
∗ Distinct file stream object must be created for each
file used, regardless of file’s type
∗ For program to both read and write to file, both an
input and output file stream object are required
∗ Input file stream objects are declared to be of type
ifstream
∗ Output file streams are declared to be of type
ofstream
A First Book of C++ 4th Edition 13
File Stream Objects (cont'd.)
∗ Each file stream object has access to methods defined for its
respective ifstream or ofstream class, including:
∗ Opening file: connecting stream object name to external
filename
∗ Determining whether a successful connection has been made
∗ Closing file: closing connection
∗ Getting next data item into program from input stream
∗ Putting new data item from program onto output stream
∗ Detecting when end of file has been reached
A First Book of C++ 4th Edition 14
File Stream Methods
∗ open() method:
∗ Establishes physical connecting link between program
and file
∗ Operating system function that is transparent to
programmer
∗ Connects file’s external computer name to stream
object name used internally by program
∗ Provided by the ifstream and ofstream classes
∗ File opened for input is said to be in read mode
A First Book of C++ 4th Edition 15
File Stream Methods (cont'd.)
∗ Example: inFile.open("prices.dat");
∗ Connects external text file named prices.dat to
internal program file stream object named inFile
∗ Accesses file using internal object name inFile
∗ Computer saves file under the external name
prices.dat
∗ Calling the open() method uses the standard object
notation: objectName.open()
A First Book of C++ 4th Edition 16
File Stream Methods (cont'd.)
user-defined variable
∗ fail() method: returns true value if file is
unsuccessfully opened, false if open succeeded
∗ Good programming practice is to check that connection
is established before using file
∗ In addition to fail() method, C++ provides three
other methods, listed in Table 9.2, that can be used to
detect file’s status
∗ Program 9.1 illustrates statements required to open
file for input, including error-checking routine to
ensure that successful open was obtained
A First Book of C++ 4th Edition 17
File Stream Methods (cont'd.)
∗ Example of use of fail() method:
//ifstream = ”input file” stream
ifstream inFile; // any object name can be used here
inFile.open("prices.dat"); // open the file
// check that the connection was opened successfully
if (inFile.fail())
{
cout << "nThe file was not successfully opened"
<< "n Please check that the file currently exists."
<< endl;
exit(1);
}
A First Book of C++ 4th Edition 18
File Stream Methods (cont'd.)
A First Book of C++ 4th Edition 19
A First Book of C++ 4th Edition 20
File Stream Methods (cont'd.)
∗ Different checking required for output files
∗ If file exists having same name as file to be opened in
output mode, existing file is erased and all data lost
∗ To avoid this situation, file is first opened in input mode
to see if it exists
∗ If it does, user is given choice of explicitly permitting it to
be overwritten (when it is later opened in output mode)
∗ Code used to accomplish this is highlighted in Program
9.2 (refer textbook)
A First Book of C++ 4th Edition 21
File Stream Methods (cont'd.)
∗ Embedding a filename in program causes problems
∗ No provision for user to enter desired filename during
program execution
∗ Any changes require modification of open() method
and recompile
∗ These problems can be solved by assigning filename
to string variable, as shown in Programs 9.3a and 9.3b
A First Book of C++ 4th Edition 22
File Stream Methods (cont'd.)
A First Book of C++ 4th Edition 23
// ask user to enter filename
// declare inFile of type ifstream (input stream)
∗ close() method: breaks connection between file’s
external name and file stream object
∗ Object can then be used for another file
∗ Good programming practice is to close files no longer
needed
∗ Operating system automatically closes any open files at
end of normal program execution
∗ Example: inFile.close(); closes inFile
stream’s connection to its current file
∗ close() method takes no argument
A First Book of C++ 4th Edition 24
File Stream Methods (cont'd.)
∗ Operations similar to reading input from keyboard and
writing data to display screen
∗ For writing to file, the cout object is replaced by ofstream
object name declared in program
∗ Example: if outFile is declared as object of type
ofstream, the following output statement is valid:
outFile << descrip << ' ' << price;
∗ The filename directs output stream to file instead of standard
display device
∗ Example: Program 9.4
A First Book of C++ 4th Edition 25
Reading and Writing Text Files
A First Book of C++ 4th Edition 26
Program 9.4
A First Book of C++ 4th Edition 27
Program 9.4(cont…)
∗ Program 9.4 output:
∗ File named prices.dat is created and saved by
computer as text file (the default file type)
∗ prices.dat is sequential file consisting of the
following data:
Mats 39.95
Bulbs 3.22
Fuses 1.08
∗ Actual storage of characters in file depends on character
codes used by computer
∗ Output file contains 36 characters (Figure 9.2)
A First Book of C++ 4th Edition 28
Reading and Writing Text Files
(cont'd.)
A First Book of C++ 4th Edition 29
Reading and Writing Text Files
(cont'd.)
∗ Almost identical to reading data from standard
keyboard
∗ cin object replaced by ifstream object declared in
program
∗ Example: the input statement:
inFile >> descrip >> price;
reads next two items in file and stores them in variables
descrip and price
∗ File stream name directs input to come from file stream
rather than the keyboard
A First Book of C++ 4th Edition 30
Reading from a Text File
∗ Program 9.5 illustrates how the prices.dat file
created in Program 9.4 can be read
∗ Also illustrates method of detecting end-of-file (EOF)
marker using good() function (see Table 9.2)
∗ Other methods that can be used for stream input are
listed in Table 9.3
∗ Each method must be preceded by stream object name
A First Book of C++ 4th Edition 31
Reading from a Text File (cont'd.)
A First Book of C++ 4th Edition 32
Program 9.5
#include <iostream>
#include <fstream> // file stream
#include <cstdlib> // needed for exit
#include <string>
using namespace std;
int main(){
string filename = "prices.dat"; // put the filename up front
string descrip;
double price;
ifstream inFile;
inFile.open(filename.c_str());
if(inFile.fail()) { // check for successful open
cout << "The file is not successfully opened"
<< "n Please check that the file currently exists."
<< endl;
exit(1);
}
A First Book of C++ 4th Edition 33
Program 9.5 (cont…)
//read and display file’s contents
inFile >> descrip >> price;
while (inFile.good()) // check next character
{
cout << descrip << ' ' << price << endl;
inFile >> descrip >> price;
}
inFile.close();
return 0;
}
A First Book of C++ 4th Edition 34
Reading from a Text File (cont'd.)
∗ C++ supports logical and physical file objects
∗ Logical file object: stream that connects file of logically
related data (data file) to a program
∗ Physical file object: stream that connects to hardware
device such as keyboard or printer
∗ Standard input file: physical device assigned to
program for data entry
∗ Standard output file: physical device on which output
is automatically displayed
A First Book of C++ 4th Edition 35
Standard Device Files
∗ The keyboard, display, error, and log streams are
automatically connected to the stream objects named
cin, cout, cerr, clog
∗ Requires iostream header file
∗ Other devices can be used if the name assigned by system
is known
∗ Example: most personal computers assign name prn to
printer connected to computer
∗ Statement outFile.open("prn") connects printer to
ofstream object named outFile
A First Book of C++ 4th Edition 36
Other Devices
∗ File access: retrieving data from file
∗ File organization: the way data is stored in a file
∗ Sequential organization: characters in file are stored
in sequential manner, one after another
∗ Random access: any character in an open file can be
read directly without having to read characters ahead
of it
A First Book of C++ 4th Edition 37
Random File Access
∗ File position marker: long integer that represents an offset
from the beginning of each file
∗ Keeps track of where next character is to be read from or
written to
∗ Allows for random access of any individual character
∗ Table 9.4 shows functions used to access and change the
file position marker
∗ Program 9.7 illustrates use of seekg() and tellg() to
read and display file in reverse order (refer textbook, Pg
418)
A First Book of C++ 4th Edition 38
Random File Access (cont'd.)
A First Book of C++ 4th Edition 39
A First Book of C++ 4th Edition 40
Random File Access (cont'd.)
∗ A file stream object can be used as function argument
∗ Function’s formal parameter must be a reference (see
Section 6.3) to correct stream, either as ifstream& or
ofstream&
∗ Example: Program 9.8
∗ ofstream object named outfile is opened in
main()
∗ Stream object is passed to the function inOut()
∗ inOut() is used to write five lines of user-entered text
to file
A First Book of C++ 4th Edition 41
File Streams as Function Arguments
A First Book of C++ 4th Edition 42
Program 9.8
A First Book of C++ 4th Edition 43
Program 9.8 (cont…)
∗ Forgetting to open a file before attempting to read from it
or write to it
∗ Using file’s external name in place of internal file stream
object name when accessing file
∗ Opening file for output without first checking that file with
given name already exists
∗ Not checking for preexisting file ensures that file will be
overwritten
∗ Not understanding that end of a file is detected only after
EOF sentinel has either been read or passed over
A First Book of C++ 4th Edition 44
Common Programming Errors
∗ Attempting to detect end of file using character
variables for EOF marker
∗ Any variable used to accept EOF must be declared as an
integer variable
∗ Using integer argument with the seekg() and
seekp() functions
∗ Offset must be a long integer constant or variable
∗ Any other value passed to these functions can result in
an unpredictable result
A First Book of C++ 4th Edition 45
Common Programming Errors
(cont'd.)
∗ A data file is any collection of data stored in an
external storage medium under a common name
∗ A data file is connected to file stream using
fstream’s open() method
∗ This function connects file’s external name with internal
object name
∗ A file can be opened in input or output mode
∗ An opened output file stream either creates a new data
file or erases data in an existing opened file
A First Book of C++ 4th Edition 46
Summary
∗ All file streams must be declared as objects of either
the ifstream or ofstream classes
∗ In addition to any files opened within a function, the
standard stream objects cin, cout, and cerr are
automatically declared and opened when a program
is run
A First Book of C++ 4th Edition 47
Summary (cont'd.)
∗ Data files can be accessed randomly using the
seekg(), seekp(), tellg(), and tellp()
methods
∗ The “g” versions of these functions are used to alter
and query file position marker for input file streams
∗ The “p” versions do the same for output file streams
∗ Table 9.5 lists the methods supplied by the fstream
class for file manipulation
A First Book of C++ 4th Edition 48
Summary (cont'd.)
∗ iostream class library accesses files by using
entities called streams
∗ For most systems, the data bytes transferred on a
stream represent ASCII characters or binary numbers
∗ Mechanism for reading a byte stream from a file or
writing a byte stream to a file is hidden when using a
high-level language, such as C++
A First Book of C++ 4th Edition 49
Chapter Supplement: The iostream
Class Library
A First Book of C++ 4th Edition 50
File Stream Transfer Mechanism
A First Book of C++ 4th Edition 51
Components of the iostream Class
Library
∗ Class strstream is derived from the ios class
∗ Uses the strstreambuf class shown in Figure 9.5
∗ Requires the strstream header file
∗ Provides capabilities for writing and reading strings to and
from in-memory defined streams
∗ In-memory streams are typically used to “assemble” a
string from smaller pieces
∗ Until a complete line of characters is ready to be written to
cout or to a file
∗ Attaching a strstream object to a buffer is similar to
attaching an fstream object to an output file
A First Book of C++ 4th Edition 52
In-Memory Formatting

More Related Content

What's hot (18)

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)
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
File Pointers
File PointersFile Pointers
File Pointers
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Data file handling
Data file handlingData file handling
Data file handling
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Python file handling
Python file handlingPython file handling
Python file handling
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
File management in C++
File management in C++File management in C++
File management in C++
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File Handling
File HandlingFile Handling
File Handling
 

Viewers also liked

Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...
Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...
Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...Daniel Riley
 
winter2012partnership
winter2012partnershipwinter2012partnership
winter2012partnershipPendarvis Ben
 
Nonne di plaza de mayo- Simona Fichera
Nonne di plaza de mayo- Simona FicheraNonne di plaza de mayo- Simona Fichera
Nonne di plaza de mayo- Simona FicheraMartaMaria36
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2IIUM
 
Compare &amp; contrast vocabulary
Compare &amp; contrast vocabularyCompare &amp; contrast vocabulary
Compare &amp; contrast vocabularyhacersivil
 
Principle and Practice of Management MGT Ippt chap005
Principle and Practice of Management MGT Ippt chap005Principle and Practice of Management MGT Ippt chap005
Principle and Practice of Management MGT Ippt chap005IIUM
 
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇filizkaragozoglu
 
La Técnica Gestual para Directores de Libia Gómez
La Técnica Gestual para Directores de Libia GómezLa Técnica Gestual para Directores de Libia Gómez
La Técnica Gestual para Directores de Libia GómezFernando Archila
 
Political science cs
Political science  csPolitical science  cs
Political science csIIUM
 
Yds deneme-sinavi-2014
Yds deneme-sinavi-2014Yds deneme-sinavi-2014
Yds deneme-sinavi-2014hacersivil
 
Wish clauses(exercise)
Wish clauses(exercise)Wish clauses(exercise)
Wish clauses(exercise)hacersivil
 
o'level islamiyat book
o'level islamiyat booko'level islamiyat book
o'level islamiyat bookchjutt
 

Viewers also liked (13)

Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...
Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...
Toward an Electrically-Pumped Silicon Laser Modeling and Optimization_Thesis_...
 
winter2012partnership
winter2012partnershipwinter2012partnership
winter2012partnership
 
Nonne di plaza de mayo- Simona Fichera
Nonne di plaza de mayo- Simona FicheraNonne di plaza de mayo- Simona Fichera
Nonne di plaza de mayo- Simona Fichera
 
D grubu
D grubuD grubu
D grubu
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2
 
Compare &amp; contrast vocabulary
Compare &amp; contrast vocabularyCompare &amp; contrast vocabulary
Compare &amp; contrast vocabulary
 
Principle and Practice of Management MGT Ippt chap005
Principle and Practice of Management MGT Ippt chap005Principle and Practice of Management MGT Ippt chap005
Principle and Practice of Management MGT Ippt chap005
 
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇
Mustaki̇l resamlar ve heykeltiraşlar bi̇rli̇ği̇
 
La Técnica Gestual para Directores de Libia Gómez
La Técnica Gestual para Directores de Libia GómezLa Técnica Gestual para Directores de Libia Gómez
La Técnica Gestual para Directores de Libia Gómez
 
Political science cs
Political science  csPolitical science  cs
Political science cs
 
Yds deneme-sinavi-2014
Yds deneme-sinavi-2014Yds deneme-sinavi-2014
Yds deneme-sinavi-2014
 
Wish clauses(exercise)
Wish clauses(exercise)Wish clauses(exercise)
Wish clauses(exercise)
 
o'level islamiyat book
o'level islamiyat booko'level islamiyat book
o'level islamiyat book
 

Similar to Csc1100 lecture15 ch09

Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfstudy material
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptxVishuSaini22
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with exampleSunil Patel
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Working with the IFS on System i
Working with the IFS on System iWorking with the IFS on System i
Working with the IFS on System iChuck Walker
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfaquacare2008
 

Similar to Csc1100 lecture15 ch09 (20)

Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Working with the IFS on System i
Working with the IFS on System iWorking with the IFS on System i
Working with the IFS on System i
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
Files in c++
Files in c++Files in c++
Files in c++
 
File management
File managementFile management
File management
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File management
File managementFile management
File management
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 

More from IIUM

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhostIIUM
 
Chapter 2
Chapter 2Chapter 2
Chapter 2IIUM
 
Chapter 1
Chapter 1Chapter 1
Chapter 1IIUM
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimediaIIUM
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblockIIUM
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice keyIIUM
 
Group p1
Group p1Group p1
Group p1IIUM
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoIIUM
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009IIUM
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lformsIIUM
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answerIIUM
 
Redo midterm
Redo midtermRedo midterm
Redo midtermIIUM
 
Heaps
HeapsHeaps
HeapsIIUM
 
Report format
Report formatReport format
Report formatIIUM
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelinesIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516IIUM
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotationsIIUM
 
Week12 graph
Week12   graph Week12   graph
Week12 graph IIUM
 

More from IIUM (20)

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhost
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimedia
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice key
 
Group p1
Group p1Group p1
Group p1
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seo
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lforms
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answer
 
Redo midterm
Redo midtermRedo midterm
Redo midterm
 
Heaps
HeapsHeaps
Heaps
 
Report format
Report formatReport format
Report format
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelines
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotations
 
Week12 graph
Week12   graph Week12   graph
Week12 graph
 

Csc1100 lecture15 ch09

  • 1. A First Book of C++A First Book of C++ Chapter 9Chapter 9 I/O Streams and Data FilesI/O Streams and Data Files
  • 2. ∗ In this chapter, you will learn about: ∗ I/O File Stream Objects and Methods ∗ Reading and Writing Text Files ∗ Random File Access ∗ File Streams as Function Arguments ∗ Common Programming Errors ∗ The iostream Class Library A First Book of C++ 4th Edition 2 Objectives
  • 3. ∗ To store and retrieve data outside a C++ program, you need two things: ∗ A file ∗ A file stream object A First Book of C++ 4th Edition 3 I/O File Stream Objects and Methods
  • 4. ∗ File: collection of data stored together under common name, usually on disk, USB drive, or CD/DVD ∗ C++ programs stored on disk are examples of files ∗ Stored data in program file is the code that becomes input data to C++ compiler ∗ A C++ program is not usually considered data file ∗ Data file typically refers only to files containing the data used in C++ program A First Book of C++ 4th Edition 4 Files
  • 5. ∗ External name: unique filename for file ∗ External name is how operating system knows file ∗ Contents of directory or folder are listed by external names ∗ Each computer operating system has its own specifications for external filename size ∗ Table 9.1 lists specifications for more commonly used operating systems A First Book of C++ 4th Edition 5 Files (cont'd.)
  • 6. A First Book of C++ 4th Edition 6 Files (cont'd.)
  • 7. ∗ Use descriptive names ∗ Avoid long filenames ∗ They take more time to type and can result in typing errors ∗ Manageable length for filename is 12 to 14 characters, with maximum of 25 characters ∗ Choose filenames that indicate type of data in file and application for which it is used ∗ Frequently, first eight characters describe data, and an extension describes application A First Book of C++ 4th Edition 7 Files (cont'd.)
  • 8. ∗ Using DOS convention, the following are all valid computer data filenames: prices.dat records info.txt exper1.dat scores.dat math.mem A First Book of C++ 4th Edition 8 Files (cont'd.)
  • 9. ∗ Two basic types of files: both store data using binary code ∗ Text (character-based) files: store each character using individual character code (typically ASCII or Unicode) ∗ Advantage: allows files to be displayed by word-processing program or text editor ∗ Binary-based files: store numbers in binary form and strings in ASCII or Unicode form ∗ Advantage: provides compactness A First Book of C++ 4th Edition 9 Files (cont'd.)
  • 10. ∗ File stream: one-way transmission path used to connect a file to a program ∗ Mode (of file stream): determines whether path will move data from file into program or from program to file ∗ Input file stream: used to transfer data from a file to a program ∗ Output file stream: sends data from a program to a file A First Book of C++ 4th Edition 10 File Stream Objects
  • 11. ∗ Direction (mode) of file stream is defined in relation to program and not file: ∗ Data that goes into program are considered input data ∗ Data sent out from program are considered output data ∗ Figure 9.1 illustrates data flow from and to file using input and output file streams A First Book of C++ 4th Edition 11 File Stream Objects (cont'd.)
  • 12. A First Book of C++ 4th Edition 12 File Stream Objects (cont'd.)
  • 13. ∗ Distinct file stream object must be created for each file used, regardless of file’s type ∗ For program to both read and write to file, both an input and output file stream object are required ∗ Input file stream objects are declared to be of type ifstream ∗ Output file streams are declared to be of type ofstream A First Book of C++ 4th Edition 13 File Stream Objects (cont'd.)
  • 14. ∗ Each file stream object has access to methods defined for its respective ifstream or ofstream class, including: ∗ Opening file: connecting stream object name to external filename ∗ Determining whether a successful connection has been made ∗ Closing file: closing connection ∗ Getting next data item into program from input stream ∗ Putting new data item from program onto output stream ∗ Detecting when end of file has been reached A First Book of C++ 4th Edition 14 File Stream Methods
  • 15. ∗ open() method: ∗ Establishes physical connecting link between program and file ∗ Operating system function that is transparent to programmer ∗ Connects file’s external computer name to stream object name used internally by program ∗ Provided by the ifstream and ofstream classes ∗ File opened for input is said to be in read mode A First Book of C++ 4th Edition 15 File Stream Methods (cont'd.)
  • 16. ∗ Example: inFile.open("prices.dat"); ∗ Connects external text file named prices.dat to internal program file stream object named inFile ∗ Accesses file using internal object name inFile ∗ Computer saves file under the external name prices.dat ∗ Calling the open() method uses the standard object notation: objectName.open() A First Book of C++ 4th Edition 16 File Stream Methods (cont'd.) user-defined variable
  • 17. ∗ fail() method: returns true value if file is unsuccessfully opened, false if open succeeded ∗ Good programming practice is to check that connection is established before using file ∗ In addition to fail() method, C++ provides three other methods, listed in Table 9.2, that can be used to detect file’s status ∗ Program 9.1 illustrates statements required to open file for input, including error-checking routine to ensure that successful open was obtained A First Book of C++ 4th Edition 17 File Stream Methods (cont'd.)
  • 18. ∗ Example of use of fail() method: //ifstream = ”input file” stream ifstream inFile; // any object name can be used here inFile.open("prices.dat"); // open the file // check that the connection was opened successfully if (inFile.fail()) { cout << "nThe file was not successfully opened" << "n Please check that the file currently exists." << endl; exit(1); } A First Book of C++ 4th Edition 18 File Stream Methods (cont'd.)
  • 19. A First Book of C++ 4th Edition 19
  • 20. A First Book of C++ 4th Edition 20 File Stream Methods (cont'd.)
  • 21. ∗ Different checking required for output files ∗ If file exists having same name as file to be opened in output mode, existing file is erased and all data lost ∗ To avoid this situation, file is first opened in input mode to see if it exists ∗ If it does, user is given choice of explicitly permitting it to be overwritten (when it is later opened in output mode) ∗ Code used to accomplish this is highlighted in Program 9.2 (refer textbook) A First Book of C++ 4th Edition 21 File Stream Methods (cont'd.)
  • 22. ∗ Embedding a filename in program causes problems ∗ No provision for user to enter desired filename during program execution ∗ Any changes require modification of open() method and recompile ∗ These problems can be solved by assigning filename to string variable, as shown in Programs 9.3a and 9.3b A First Book of C++ 4th Edition 22 File Stream Methods (cont'd.)
  • 23. A First Book of C++ 4th Edition 23 // ask user to enter filename // declare inFile of type ifstream (input stream)
  • 24. ∗ close() method: breaks connection between file’s external name and file stream object ∗ Object can then be used for another file ∗ Good programming practice is to close files no longer needed ∗ Operating system automatically closes any open files at end of normal program execution ∗ Example: inFile.close(); closes inFile stream’s connection to its current file ∗ close() method takes no argument A First Book of C++ 4th Edition 24 File Stream Methods (cont'd.)
  • 25. ∗ Operations similar to reading input from keyboard and writing data to display screen ∗ For writing to file, the cout object is replaced by ofstream object name declared in program ∗ Example: if outFile is declared as object of type ofstream, the following output statement is valid: outFile << descrip << ' ' << price; ∗ The filename directs output stream to file instead of standard display device ∗ Example: Program 9.4 A First Book of C++ 4th Edition 25 Reading and Writing Text Files
  • 26. A First Book of C++ 4th Edition 26 Program 9.4
  • 27. A First Book of C++ 4th Edition 27 Program 9.4(cont…)
  • 28. ∗ Program 9.4 output: ∗ File named prices.dat is created and saved by computer as text file (the default file type) ∗ prices.dat is sequential file consisting of the following data: Mats 39.95 Bulbs 3.22 Fuses 1.08 ∗ Actual storage of characters in file depends on character codes used by computer ∗ Output file contains 36 characters (Figure 9.2) A First Book of C++ 4th Edition 28 Reading and Writing Text Files (cont'd.)
  • 29. A First Book of C++ 4th Edition 29 Reading and Writing Text Files (cont'd.)
  • 30. ∗ Almost identical to reading data from standard keyboard ∗ cin object replaced by ifstream object declared in program ∗ Example: the input statement: inFile >> descrip >> price; reads next two items in file and stores them in variables descrip and price ∗ File stream name directs input to come from file stream rather than the keyboard A First Book of C++ 4th Edition 30 Reading from a Text File
  • 31. ∗ Program 9.5 illustrates how the prices.dat file created in Program 9.4 can be read ∗ Also illustrates method of detecting end-of-file (EOF) marker using good() function (see Table 9.2) ∗ Other methods that can be used for stream input are listed in Table 9.3 ∗ Each method must be preceded by stream object name A First Book of C++ 4th Edition 31 Reading from a Text File (cont'd.)
  • 32. A First Book of C++ 4th Edition 32 Program 9.5 #include <iostream> #include <fstream> // file stream #include <cstdlib> // needed for exit #include <string> using namespace std; int main(){ string filename = "prices.dat"; // put the filename up front string descrip; double price; ifstream inFile; inFile.open(filename.c_str()); if(inFile.fail()) { // check for successful open cout << "The file is not successfully opened" << "n Please check that the file currently exists." << endl; exit(1); }
  • 33. A First Book of C++ 4th Edition 33 Program 9.5 (cont…) //read and display file’s contents inFile >> descrip >> price; while (inFile.good()) // check next character { cout << descrip << ' ' << price << endl; inFile >> descrip >> price; } inFile.close(); return 0; }
  • 34. A First Book of C++ 4th Edition 34 Reading from a Text File (cont'd.)
  • 35. ∗ C++ supports logical and physical file objects ∗ Logical file object: stream that connects file of logically related data (data file) to a program ∗ Physical file object: stream that connects to hardware device such as keyboard or printer ∗ Standard input file: physical device assigned to program for data entry ∗ Standard output file: physical device on which output is automatically displayed A First Book of C++ 4th Edition 35 Standard Device Files
  • 36. ∗ The keyboard, display, error, and log streams are automatically connected to the stream objects named cin, cout, cerr, clog ∗ Requires iostream header file ∗ Other devices can be used if the name assigned by system is known ∗ Example: most personal computers assign name prn to printer connected to computer ∗ Statement outFile.open("prn") connects printer to ofstream object named outFile A First Book of C++ 4th Edition 36 Other Devices
  • 37. ∗ File access: retrieving data from file ∗ File organization: the way data is stored in a file ∗ Sequential organization: characters in file are stored in sequential manner, one after another ∗ Random access: any character in an open file can be read directly without having to read characters ahead of it A First Book of C++ 4th Edition 37 Random File Access
  • 38. ∗ File position marker: long integer that represents an offset from the beginning of each file ∗ Keeps track of where next character is to be read from or written to ∗ Allows for random access of any individual character ∗ Table 9.4 shows functions used to access and change the file position marker ∗ Program 9.7 illustrates use of seekg() and tellg() to read and display file in reverse order (refer textbook, Pg 418) A First Book of C++ 4th Edition 38 Random File Access (cont'd.)
  • 39. A First Book of C++ 4th Edition 39
  • 40. A First Book of C++ 4th Edition 40 Random File Access (cont'd.)
  • 41. ∗ A file stream object can be used as function argument ∗ Function’s formal parameter must be a reference (see Section 6.3) to correct stream, either as ifstream& or ofstream& ∗ Example: Program 9.8 ∗ ofstream object named outfile is opened in main() ∗ Stream object is passed to the function inOut() ∗ inOut() is used to write five lines of user-entered text to file A First Book of C++ 4th Edition 41 File Streams as Function Arguments
  • 42. A First Book of C++ 4th Edition 42 Program 9.8
  • 43. A First Book of C++ 4th Edition 43 Program 9.8 (cont…)
  • 44. ∗ Forgetting to open a file before attempting to read from it or write to it ∗ Using file’s external name in place of internal file stream object name when accessing file ∗ Opening file for output without first checking that file with given name already exists ∗ Not checking for preexisting file ensures that file will be overwritten ∗ Not understanding that end of a file is detected only after EOF sentinel has either been read or passed over A First Book of C++ 4th Edition 44 Common Programming Errors
  • 45. ∗ Attempting to detect end of file using character variables for EOF marker ∗ Any variable used to accept EOF must be declared as an integer variable ∗ Using integer argument with the seekg() and seekp() functions ∗ Offset must be a long integer constant or variable ∗ Any other value passed to these functions can result in an unpredictable result A First Book of C++ 4th Edition 45 Common Programming Errors (cont'd.)
  • 46. ∗ A data file is any collection of data stored in an external storage medium under a common name ∗ A data file is connected to file stream using fstream’s open() method ∗ This function connects file’s external name with internal object name ∗ A file can be opened in input or output mode ∗ An opened output file stream either creates a new data file or erases data in an existing opened file A First Book of C++ 4th Edition 46 Summary
  • 47. ∗ All file streams must be declared as objects of either the ifstream or ofstream classes ∗ In addition to any files opened within a function, the standard stream objects cin, cout, and cerr are automatically declared and opened when a program is run A First Book of C++ 4th Edition 47 Summary (cont'd.)
  • 48. ∗ Data files can be accessed randomly using the seekg(), seekp(), tellg(), and tellp() methods ∗ The “g” versions of these functions are used to alter and query file position marker for input file streams ∗ The “p” versions do the same for output file streams ∗ Table 9.5 lists the methods supplied by the fstream class for file manipulation A First Book of C++ 4th Edition 48 Summary (cont'd.)
  • 49. ∗ iostream class library accesses files by using entities called streams ∗ For most systems, the data bytes transferred on a stream represent ASCII characters or binary numbers ∗ Mechanism for reading a byte stream from a file or writing a byte stream to a file is hidden when using a high-level language, such as C++ A First Book of C++ 4th Edition 49 Chapter Supplement: The iostream Class Library
  • 50. A First Book of C++ 4th Edition 50 File Stream Transfer Mechanism
  • 51. A First Book of C++ 4th Edition 51 Components of the iostream Class Library
  • 52. ∗ Class strstream is derived from the ios class ∗ Uses the strstreambuf class shown in Figure 9.5 ∗ Requires the strstream header file ∗ Provides capabilities for writing and reading strings to and from in-memory defined streams ∗ In-memory streams are typically used to “assemble” a string from smaller pieces ∗ Until a complete line of characters is ready to be written to cout or to a file ∗ Attaching a strstream object to a buffer is similar to attaching an fstream object to an output file A First Book of C++ 4th Edition 52 In-Memory Formatting