Code to Demonstrate Basic File Processing
// Basic File Handling
// File: fileio3.cpp
// Files names recevied from user
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <fstream.h>
typedef char String[40];
void GetFileName(String prompt, String fileName);
int main()
{ String fileName;
GetFileName("Please enter the file containing the person database.", fileName);
ifstream inputData (fileName);
if (!inputData)
{ cout << "Cannot open input file\n";
exit(1);
}
String name;
String phoneNo;
String dummy;
int age;
double height;
GetFileName("Please enter the file in which to save the person database.", fileName);
ofstream outputData (fileName);
if (!outputData)
{ cout << "Cannot open output file\n";
exit(1);
}
outputData << setiosflags(ios::fixed);
outputData << setprecision(2);
outputData << setiosflags(ios::left) << setw(30) << "Name"
<< setiosflags(ios::right)
<< setw(16) << "Phone Number"
<< setw(6) << "Age" << setw(10) << "Height" << endl;
inputData.ignore(133, '\n');
inputData.get(name, 30);
inputData >> phoneNo;
inputData >> age;
inputData >> height;
inputData.getline(dummy, 80);
outputData << setw(30) << setiosflags(ios::left) << name
<< setiosflags(ios::right)
<< setw(16) << phoneNo
<< setw(6) << age << setw(10) << height << endl;
inputData.get(name, 30);
inputData >> phoneNo;
inputData >> age;
inputData >> height;
inputData.getline(dummy, 80);
outputData << setw(30) << setiosflags(ios::left) << name
<< setiosflags(ios::right)
<< setw(16) << phoneNo
<< setw(6) << age << setw(10) << height << endl;
cout << "Program Terminating";
return 0;
}
void GetFileName(String prompt, String fileName)
{ cout << endl; // just to make space
cout << prompt << endl;
cin.getline(fileName, 40);
}