SlideShare a Scribd company logo
1 of 22
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input and Output
3.14
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input and
Output
• The programs you have written so far
require you to re-enter data each time the
program runs.
• This is because the data stored in RAM
disappears once the program stops
running or the computer is shut down.
• If a program is to retain data between the
times it runs, it must have a way of saving
it.
3-2
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input and
Output
• Data is saved in a file, which is usually
stored on a computer’s disk.
• Once the data is saved in a file, it will
remain there after the program stops
running.
• The data can then be retrieved and used at
a later time.
3-3
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input and
Output
• There are always three steps that must be
taken when a file is used by a program:
1. The file must be opened. If the file does not
yet exist, opening it means creating it.
2. Data is then saved to the file, read from the
file, or both. (use file for read/write/ both)
3. When the program is finished using the file,
the file must be closed.
3-5
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-6
Files: What is Needed
• Use fstream header file for file access
• File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
• Define file stream objects:
ifstream infile;
ofstream outfile;
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-7
Opening Files
• Create a link between file name (outside the program)
and file stream object (inside the program)
• Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
• Filename may include drive, path info.
• Output file will be created if necessary; existing file
will be erased first
• Input file must exist for open to work
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Opening files
• Often, when opening a file, you will need to
specify its location as well as its name.
• For example, on a Windows system the
following statement opens the file
C:datainventory.dat:
– outputFile.open("C:datainventory.dat")
• In this statement, the file C:datainventory.dat is
opened and linked with outputFile.
3-8
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-9
Using Files
• Can use output file object and << to send
data to a file:
outfile << "Inventory report";
• Can use input file object and >> to copy
data from file to variables:
infile >> partNum;
infile >> qtyInStock >> qtyOnOrder;
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-10
Closing Files
• Use the close member function:
infile.close();
outfile.close();
• Don’t wait for operating system to close
files at program end
– Closing a file causes any unsaved data that
may still be held in a buffer to be saved to its
file.
– Some operating systems limit the number of
files that may be open at one time.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-11
Continued…
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-12
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-13
Continued…
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-14
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Testing for File Open Errors
4.16
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-16
Testing for File Open Errors
• Can test a file stream object to detect if an
open operation failed:
infile.open("test.txt");
if (!infile)
{
cout << "File open failure!";
}
• Can also use the fail member function
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Fail member function
ifstream inputFile;
inputFile.open("customers.txt");
if (inputFile.fail())
{
cout << "Error opening file.n";
}
The fail member function returns true when an
attempted file operation is unsuccessful.
4-17
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using a Loop to Read Data from a File
5.9
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-19
Using a Loop to Read
Data from a File
• The stream extraction operator >> returns
true when a value was successfully read,
false otherwise
• Can be tested in a while loop to continue
execution as long as values are read from
the file:
while (inputFile >> number) ...
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-20
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-21
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-22
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-23

More Related Content

Viewers also liked (9)

Christopher Wood's Resume
Christopher Wood's ResumeChristopher Wood's Resume
Christopher Wood's Resume
 
Mi collage personal martinez torres
Mi collage personal martinez torresMi collage personal martinez torres
Mi collage personal martinez torres
 
Senior Leadership Team Presentation
Senior Leadership Team PresentationSenior Leadership Team Presentation
Senior Leadership Team Presentation
 
CHAMPS
CHAMPSCHAMPS
CHAMPS
 
the cv.
the cv.the cv.
the cv.
 
Resume
ResumeResume
Resume
 
Curriculum+Vitae+Petra+Hasper+6-1
Curriculum+Vitae+Petra+Hasper+6-1Curriculum+Vitae+Petra+Hasper+6-1
Curriculum+Vitae+Petra+Hasper+6-1
 
Kafer akbid paramata
Kafer akbid paramataKafer akbid paramata
Kafer akbid paramata
 
Halaman sampul target
Halaman sampul targetHalaman sampul target
Halaman sampul target
 

Similar to File I/O in C++ Learn Basics Open Read Write

Similar to File I/O in C++ Learn Basics Open Read Write (20)

Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
Savitch Ch 06
Savitch Ch 06Savitch Ch 06
Savitch Ch 06
 
Savitch Ch 06
Savitch Ch 06Savitch Ch 06
Savitch Ch 06
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
finally.c.ppt
finally.c.pptfinally.c.ppt
finally.c.ppt
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
File handling
File handlingFile handling
File handling
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

File I/O in C++ Learn Basics Open Read Write

  • 1. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output 3.14
  • 2. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output • The programs you have written so far require you to re-enter data each time the program runs. • This is because the data stored in RAM disappears once the program stops running or the computer is shut down. • If a program is to retain data between the times it runs, it must have a way of saving it. 3-2
  • 3. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output • Data is saved in a file, which is usually stored on a computer’s disk. • Once the data is saved in a file, it will remain there after the program stops running. • The data can then be retrieved and used at a later time. 3-3
  • 4. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output • There are always three steps that must be taken when a file is used by a program: 1. The file must be opened. If the file does not yet exist, opening it means creating it. 2. Data is then saved to the file, read from the file, or both. (use file for read/write/ both) 3. When the program is finished using the file, the file must be closed. 3-5
  • 5. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-6 Files: What is Needed • Use fstream header file for file access • File stream types: ifstream for input from a file ofstream for output to a file fstream for input from or output to a file • Define file stream objects: ifstream infile; ofstream outfile;
  • 6. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-7 Opening Files • Create a link between file name (outside the program) and file stream object (inside the program) • Use the open member function: infile.open("inventory.dat"); outfile.open("report.txt"); • Filename may include drive, path info. • Output file will be created if necessary; existing file will be erased first • Input file must exist for open to work
  • 7. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Opening files • Often, when opening a file, you will need to specify its location as well as its name. • For example, on a Windows system the following statement opens the file C:datainventory.dat: – outputFile.open("C:datainventory.dat") • In this statement, the file C:datainventory.dat is opened and linked with outputFile. 3-8
  • 8. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-9 Using Files • Can use output file object and << to send data to a file: outfile << "Inventory report"; • Can use input file object and >> to copy data from file to variables: infile >> partNum; infile >> qtyInStock >> qtyOnOrder;
  • 9. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-10 Closing Files • Use the close member function: infile.close(); outfile.close(); • Don’t wait for operating system to close files at program end – Closing a file causes any unsaved data that may still be held in a buffer to be saved to its file. – Some operating systems limit the number of files that may be open at one time.
  • 10. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-11 Continued…
  • 11. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-12
  • 12. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-13 Continued…
  • 13. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-14
  • 14. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Testing for File Open Errors 4.16
  • 15. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-16 Testing for File Open Errors • Can test a file stream object to detect if an open operation failed: infile.open("test.txt"); if (!infile) { cout << "File open failure!"; } • Can also use the fail member function
  • 16. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fail member function ifstream inputFile; inputFile.open("customers.txt"); if (inputFile.fail()) { cout << "Error opening file.n"; } The fail member function returns true when an attempted file operation is unsuccessful. 4-17
  • 17. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a Loop to Read Data from a File 5.9
  • 18. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-19 Using a Loop to Read Data from a File • The stream extraction operator >> returns true when a value was successfully read, false otherwise • Can be tested in a while loop to continue execution as long as values are read from the file: while (inputFile >> number) ...
  • 19. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-20
  • 20. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-21
  • 21. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-22
  • 22. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-23