Professional Documents
Culture Documents
PF Week 10
PF Week 10
Programming Fundamentals
Lecture - 29 & 30
File Handling in C++
Learning Objectives
Upon completion of this material, you should
be able to:
•Learn about Reading data from files to variables
•Explore how to Reading data from files to Arrays
•Learn about Writing data from variables to files
•Discover how to Writing data from Arrays to files
9
Manipulators
11
Example with File Input
#include <iostream>
cout << setw(4)
#include <fstream> << ival << " ";
#include <string> cout << setw(12)
#include <iomanip> << fval << " ";
cout << left;
using namespace std; cout << setw(10)
int main() << name << endl;
{ }
ifstream input; return(0);
}
int loops, ival, i;
float fval; mydata.txt file:
string name; 5
8 9.3 Jon
cout << showpoint 6 14.335 Bill
<< scientific 0 35.67e9 Mary
<< setprecision(2); -23 -4.55 Smith
-3 -4e3 xyz
input.open("mydata.txt"); Output:
input >> loops; 8 9.30e+00 Jon
for (i=0; i < loops; i++) 6 1.43e+01 Bill
0 3.57e+10 Mary
{
-23 -4.55e+00 Smith
input >> ival; -3 -4.00e+03 xyz
input >> fval;
input >> name;
cout << right;
12
Summary
• Data in Main Memory is “volatile”
• File: Place for “permanent” data storage
• The Manipulators are used to format output
neatly