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

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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Recently uploaded (20)

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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
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...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

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