SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
An Introduction To Software
Development Using C++
Class #21:
Files
Say Hello To Homework #4!
• Last design did not work out – overloaded the traffic light
processors. Going back to HW#2 solution.
• Mayor’s son collected traffic data.
• The city would like you to use the mayor's son's file to
simulate the traffic pattern that happened on that day. They
are interested in having you calculate several values:
– How many cars came from each direction.
– The maximum size of the line of cars that had to wait to get through
the light.
– How long each car had to wait to make it through the stoplight.
– The average amount of time that cars wait based on which direction
they are coming from (four values)
Data, Data, Data
• In the real world, your program will need to process data. A
lot of data.
• In this class we’ve already used two different ways to get data
into your programs:
– You typed it in (“input”)
– It was given to you in the form of constants (6 seconds, 9 seconds,
12 seconds)
• Now it’s time to deal with A LOT OF DATA.
• Say hello to files…
Image Credit: paulmjohnstone.wordpress.com
What Is A File?
• C++ considers a file just a sequence of bytes
• Each file ends either with an end-of-file marker or at a
specific byte number recorded in an operating-system-
maintained, administrative data structure.
• When a file is opened, an object is created, and a
stream is associated with the object
How Do We Teach C++ How To Get
Data From A File
• The standard I/O header file, iostream, contains the
data types and variables that are used only for input
from a standard input device and output to a
standard output device.
• C++ provides a header file called fstream which is
used for file I/O
Image Credit: www.petbucket.com
The 5 Step File I/O Process
1. Include the header file fstream in the
program.
2. Declare file stream variables.
3. Associate the file stream variables with the
input/output sources.
4. Use the file stream variables with >>, << or
other input / output functions.
5. Close the files.
Image Credit: www2.exacq.com
Step #1: the header file fstream in the
program
• The following statement accomplishes this
task:
#include <fstream>
Image Credit: sivers.org
Step #2: Declare file stream variables
• Consider the following statements:
ifstream indata;
ofstream outdata;
• The first statement declares indata to be an
input file stream variable.
• The second statement declares outdata to be
an output file stream variable.
Image Credit: temporaexcel.blogspot.com
Step #3: Associate the file stream variables
with the input/output sources
• This step is called “opening the files”
• The stream member function
open is used to open files.
• The syntax for opening a file is:
fileStreamVariable.open(sourceName);
• Here fileStreamVariable is a file stream variable
and sourceName is a file name.
Image Credit: f2.washington.edu
Example Of Opening Files
• Assume input data is stored in a file called
prog.dat and prog.out is to be used for output.
• The following statements open prog.dat for
input and prog.out for output.
inData.open(“prog.dat”);
outData.open(“prog.out”);
Image Credit: blogs.voices.com
Dealing With
• If the input / output files are located in the same subdirectory as
the C++ source code file, then you do not have to specify the path –
just a file name.
• If the input / output file is located in a different subdirectory, then
you must specify both a path and file name.
• If our data file was located on a flash memory in drive H, then we
would have to use the statement:
inData.open(“h:prog.dat”);
• Note the use of two “” – “” is an
escape character and so to produce
• a “” you need to use “”.
Image Credit: www.career-line.com
Step 4: Use the file stream variables with
>>, << or other input / output functions
• You use the file stream variables with >>, << or other input /
output functions.
• The syntax for using >> or << with file stream variables is
exactly the same as the syntax for using them with cin and
cout.
• However, instead of using cin or cout,
you use the file stream variables that
were declared.
Image Credit: www.dreamstime.com
Examples Of File Input / Output
• Example: indata >> payrate;
reads data from the file prog.dat and stores it in the variable payrate
• outdata << “The paycheck is: $” << pay << endl;
stores the output The paycheck is $565.78 – in the file prog.out.
• The following code reads one character from a file:
char c;
while (indata.get(c)) // loop getting single characters
cout << c;
• The following code reads one line from a file:
string s;
while (getline(indata,s)) // loop getting lines
cout << s;
Image Credit: groups.etown.eduHW #4 checker
Step 5: Close the files
• Closing a file means that the file stream variables are
disassociated from the storage area and are freed.
• Once freed, they can be used for other file I/O.
• Closing an output file ensures that the entire output is sent
to the file – the buffer is emptied.
• You close files by using the stream function close
• Example:
indata.close()
outdata.close()
Image Credit: depositphotos.com
The Existence Of Files
• In the case of an input file, the file must exist before the open statement
executes.
• If the file does not exist, then the open statement fails and the input
stream enters the fail state.
– Once a failure has occurred, you must use the function clear to restore the
input stream to a working state.
• An output file does not have to exist before it is opened.
• If the output file does not exist, then the system prepares an empty file for
output.
• If the output file does exist, then
by default its old contents are erased
upon being opened.
Image Credit: warpandwoof.org
How To NOT Destroy An Output File
• To add output to the end of an existing file, you can use the
option ios::app as follows.
• Suppose that outData is declared as before and you want
to add the output to the end of the existing file, say
firstProg.out.
• The statement to open this file is:
outData.open(“firstProg.out”, ios::app);
• If the file firstProg.out does not
exist, the system simply creates
an empty file.
Image Credit: www.entrepreneur.com
How To Move Around In Both
An Input And An Output File
• Both input and output files provide member functions for
repositioning the file-position pointer (the byte number of
the next byte in the file to be read or written).
• These member functions are seekg (“seek get”) for input
and seekp (“seek put”) for output.
• Each input object has a get pointer, which indicates the
byte number in the file from which the next input is to
occur, and each output object has a put pointer, which
indicates the byte number in the file at which the next
output should be placed.
Image Credit: www.ihatepresentations.com
How To Move Around In
An Input File
• The statement: inClientFile.seekg( 0 );
repositions the file-position pointer to the beginning of the file
(location 0) attached to inClientFile.
• A second argument can be specified to indicate the seek direction,
which can be ios::beg (the default) for positioning relative to the
beginning of a stream, ios::cur for positioning relative to the current
position in a tream or ios::end for positioning relative to the end of
a stream.
• The file-position pointer is an integer value that specifies the
location in the file as a number of bytes from the file’s starting
location (this is also referred to as the offset from the beginning of
the file).
Image Credit: www.ihatepresentations.com
How To Move Around In An Input File
• Some examples of positioning the get file-
position pointer are:
Image Credit: www.salon.com
How To Move Around In
An Output File
• The same operations can be performed using
output member function seekp.
• Member functions tellg and tellp are provided to
return the current locations of the get
and put pointers, respectively.
• The following statement assigns the get file-
position pointer value to a variable:
location = fileObject.tellg();
Image Credit: www.salon.com
In Class Programming Challenge:
MLK’s “I Have A Dream Speech”
• Open the file that contains Dr. King’s “I have a dream” speech.
• Read in each line and print the number
of times that you find the words “I”, “we”,
“dream”, and “freedom”.
• Print the total number of words in the
speech.
• Write a version of this speech out to a file
with HTML paragraph formatting: “<p>”
at the start of the paragraph and “</p>”
at the end of each paragraph.
Image Credit: http://www.americanrhetoric.com/speeches/mlkihaveadream.htm
What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For do…While Break /
Continue
Arrays Functions

Mais conteúdo relacionado

Mais procurados

Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQDoncho Minkov
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python FundamentalsPraveen M Jigajinni
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to javaKalai Selvi
 
Feature Extraction for Large-Scale Text Collections
Feature Extraction for Large-Scale Text CollectionsFeature Extraction for Large-Scale Text Collections
Feature Extraction for Large-Scale Text CollectionsSease
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsJoshua Erney
 
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesIntro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesBlue Elephant Consulting
 

Mais procurados (20)

Unit VI
Unit VI Unit VI
Unit VI
 
Savitch Ch 06
Savitch Ch 06Savitch Ch 06
Savitch Ch 06
 
Language Integrated Query - LINQ
Language Integrated Query - LINQLanguage Integrated Query - LINQ
Language Integrated Query - LINQ
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Savitch ch 06
Savitch ch 06Savitch ch 06
Savitch ch 06
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Class and object
Class and objectClass and object
Class and object
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
098ca session7 c++
098ca session7 c++098ca session7 c++
098ca session7 c++
 
Inheritance
Inheritance Inheritance
Inheritance
 
Python libraries
Python librariesPython libraries
Python libraries
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to java
 
Feature Extraction for Large-Scale Text Collections
Feature Extraction for Large-Scale Text CollectionsFeature Extraction for Large-Scale Text Collections
Feature Extraction for Large-Scale Text Collections
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language Fundamentals
 
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & PrototypesIntro To C++ - Class 07 - Headers, Interfaces, & Prototypes
Intro To C++ - Class 07 - Headers, Interfaces, & Prototypes
 
Jena
JenaJena
Jena
 

Semelhante a C++ File I/O: Read Traffic Data and Simulate Patterns

Semelhante a C++ File I/O: Read Traffic Data and Simulate Patterns (20)

Data file handling
Data file handlingData file handling
Data file handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
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)
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
File upload php
File upload phpFile upload php
File upload php
 
An Introduction To Python - Modules & Solving Real World Problems
An Introduction To Python - Modules & Solving Real World ProblemsAn Introduction To Python - Modules & Solving Real World Problems
An Introduction To Python - Modules & Solving Real World Problems
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
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
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
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]
 
CPP17 - File IO
CPP17 - File IOCPP17 - File IO
CPP17 - File IO
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
 

Último

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 

Último (20)

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
CARNAVAL COM MAGIA E EUFORIA _
CARNAVAL COM MAGIA E EUFORIA            _CARNAVAL COM MAGIA E EUFORIA            _
CARNAVAL COM MAGIA E EUFORIA _
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 

C++ File I/O: Read Traffic Data and Simulate Patterns

  • 1. An Introduction To Software Development Using C++ Class #21: Files
  • 2. Say Hello To Homework #4! • Last design did not work out – overloaded the traffic light processors. Going back to HW#2 solution. • Mayor’s son collected traffic data. • The city would like you to use the mayor's son's file to simulate the traffic pattern that happened on that day. They are interested in having you calculate several values: – How many cars came from each direction. – The maximum size of the line of cars that had to wait to get through the light. – How long each car had to wait to make it through the stoplight. – The average amount of time that cars wait based on which direction they are coming from (four values)
  • 3. Data, Data, Data • In the real world, your program will need to process data. A lot of data. • In this class we’ve already used two different ways to get data into your programs: – You typed it in (“input”) – It was given to you in the form of constants (6 seconds, 9 seconds, 12 seconds) • Now it’s time to deal with A LOT OF DATA. • Say hello to files… Image Credit: paulmjohnstone.wordpress.com
  • 4. What Is A File? • C++ considers a file just a sequence of bytes • Each file ends either with an end-of-file marker or at a specific byte number recorded in an operating-system- maintained, administrative data structure. • When a file is opened, an object is created, and a stream is associated with the object
  • 5. How Do We Teach C++ How To Get Data From A File • The standard I/O header file, iostream, contains the data types and variables that are used only for input from a standard input device and output to a standard output device. • C++ provides a header file called fstream which is used for file I/O Image Credit: www.petbucket.com
  • 6. The 5 Step File I/O Process 1. Include the header file fstream in the program. 2. Declare file stream variables. 3. Associate the file stream variables with the input/output sources. 4. Use the file stream variables with >>, << or other input / output functions. 5. Close the files. Image Credit: www2.exacq.com
  • 7. Step #1: the header file fstream in the program • The following statement accomplishes this task: #include <fstream> Image Credit: sivers.org
  • 8. Step #2: Declare file stream variables • Consider the following statements: ifstream indata; ofstream outdata; • The first statement declares indata to be an input file stream variable. • The second statement declares outdata to be an output file stream variable. Image Credit: temporaexcel.blogspot.com
  • 9. Step #3: Associate the file stream variables with the input/output sources • This step is called “opening the files” • The stream member function open is used to open files. • The syntax for opening a file is: fileStreamVariable.open(sourceName); • Here fileStreamVariable is a file stream variable and sourceName is a file name. Image Credit: f2.washington.edu
  • 10. Example Of Opening Files • Assume input data is stored in a file called prog.dat and prog.out is to be used for output. • The following statements open prog.dat for input and prog.out for output. inData.open(“prog.dat”); outData.open(“prog.out”); Image Credit: blogs.voices.com
  • 11. Dealing With • If the input / output files are located in the same subdirectory as the C++ source code file, then you do not have to specify the path – just a file name. • If the input / output file is located in a different subdirectory, then you must specify both a path and file name. • If our data file was located on a flash memory in drive H, then we would have to use the statement: inData.open(“h:prog.dat”); • Note the use of two “” – “” is an escape character and so to produce • a “” you need to use “”. Image Credit: www.career-line.com
  • 12. Step 4: Use the file stream variables with >>, << or other input / output functions • You use the file stream variables with >>, << or other input / output functions. • The syntax for using >> or << with file stream variables is exactly the same as the syntax for using them with cin and cout. • However, instead of using cin or cout, you use the file stream variables that were declared. Image Credit: www.dreamstime.com
  • 13. Examples Of File Input / Output • Example: indata >> payrate; reads data from the file prog.dat and stores it in the variable payrate • outdata << “The paycheck is: $” << pay << endl; stores the output The paycheck is $565.78 – in the file prog.out. • The following code reads one character from a file: char c; while (indata.get(c)) // loop getting single characters cout << c; • The following code reads one line from a file: string s; while (getline(indata,s)) // loop getting lines cout << s; Image Credit: groups.etown.eduHW #4 checker
  • 14. Step 5: Close the files • Closing a file means that the file stream variables are disassociated from the storage area and are freed. • Once freed, they can be used for other file I/O. • Closing an output file ensures that the entire output is sent to the file – the buffer is emptied. • You close files by using the stream function close • Example: indata.close() outdata.close() Image Credit: depositphotos.com
  • 15. The Existence Of Files • In the case of an input file, the file must exist before the open statement executes. • If the file does not exist, then the open statement fails and the input stream enters the fail state. – Once a failure has occurred, you must use the function clear to restore the input stream to a working state. • An output file does not have to exist before it is opened. • If the output file does not exist, then the system prepares an empty file for output. • If the output file does exist, then by default its old contents are erased upon being opened. Image Credit: warpandwoof.org
  • 16. How To NOT Destroy An Output File • To add output to the end of an existing file, you can use the option ios::app as follows. • Suppose that outData is declared as before and you want to add the output to the end of the existing file, say firstProg.out. • The statement to open this file is: outData.open(“firstProg.out”, ios::app); • If the file firstProg.out does not exist, the system simply creates an empty file. Image Credit: www.entrepreneur.com
  • 17. How To Move Around In Both An Input And An Output File • Both input and output files provide member functions for repositioning the file-position pointer (the byte number of the next byte in the file to be read or written). • These member functions are seekg (“seek get”) for input and seekp (“seek put”) for output. • Each input object has a get pointer, which indicates the byte number in the file from which the next input is to occur, and each output object has a put pointer, which indicates the byte number in the file at which the next output should be placed. Image Credit: www.ihatepresentations.com
  • 18. How To Move Around In An Input File • The statement: inClientFile.seekg( 0 ); repositions the file-position pointer to the beginning of the file (location 0) attached to inClientFile. • A second argument can be specified to indicate the seek direction, which can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a tream or ios::end for positioning relative to the end of a stream. • The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location (this is also referred to as the offset from the beginning of the file). Image Credit: www.ihatepresentations.com
  • 19. How To Move Around In An Input File • Some examples of positioning the get file- position pointer are: Image Credit: www.salon.com
  • 20. How To Move Around In An Output File • The same operations can be performed using output member function seekp. • Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. • The following statement assigns the get file- position pointer value to a variable: location = fileObject.tellg(); Image Credit: www.salon.com
  • 21. In Class Programming Challenge: MLK’s “I Have A Dream Speech” • Open the file that contains Dr. King’s “I have a dream” speech. • Read in each line and print the number of times that you find the words “I”, “we”, “dream”, and “freedom”. • Print the total number of words in the speech. • Write a version of this speech out to a file with HTML paragraph formatting: “<p>” at the start of the paragraph and “</p>” at the end of each paragraph. Image Credit: http://www.americanrhetoric.com/speeches/mlkihaveadream.htm
  • 22. What’s In Your C++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline While For do…While Break / Continue Arrays Functions

Notas do Editor

  1. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.