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

Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
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
lailoesakhan
 

Similar to File (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

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 

File

  • 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