Files For Data Handling: Check Validity of File Opening Writing Data Onto Files Reading Data From Files
Files For Data Handling: Check Validity of File Opening Writing Data Onto Files Reading Data From Files
Files For Data Handling: Check Validity of File Opening Writing Data Onto Files Reading Data From Files
HANDLING
Learning outcomes:
Solution:
Use file processing/handling
2
Examples:
You are given a file containing vehicle types and their
plate numbers for a project in which you have to separate
the plate numbers according to the type of vehicle, i.e.
cars, vans, motorcycle, lorry, etc.
Advantages:
Accuracy Without data file processing features,
mistakes may occur in a work done using manual hands
and naked eyes.
2.
(cont)
3.
4.
E.g.
ofstream file_out (outputfile.dat);
float Number1=45.4;
float Number2=99.8;
for (int i=1; i <= 5; i++)
file_out << Number1 <<\t<<Number2<< endl;
file_out.close();
9
Example :
How to read unknown number of
data with unknown datatype?
Create a text data file by typing your name, and address lines
on separate lines. Save the file as name filein.dat.
Then, type the code segment below in a main program,
compile and run. NOTE: Do not forget to include header
file <fstream>
ifstream file_in (filein.dat);
char data[100];
// string data; // alternative method using string
for (int i=1; !file_in.eof(); i++) {
file_in.getline(data,100);
// getline(file_in,data); using string
cout << endl << "\t" << i << "\t" << data;}
cout << "\n\n\tEnd ofEEE123,
file!";
by Assoc Prof Dr Junita
Mohamad Saleh
13
file_in.close();
Function call
Check_openFile(file_id);
Function header
void Check_openFile(ofstream& file_id);
15