When you write _DecimalT template-class constants to a file, scan them back into a _DecimalT template-class, and then pass the _DecimalT template-class array to a function with printf(). If the file cannot be opened, or if the contents of the array are not valid, an error message is generated.
The following figure provides an example.
Figure 315. Example of Writing _DecimalT Class Template Constants to a File
|
The output is:
+--------------------------------------------------------------------------------+ |b[0]=12.35 | |b[1]=25.00 | |b[2]=-19.58 | +--------------------------------------------------------------------------------+
You can rewrite this program to use the ofstream class, as shown in the following figure:
Figure 316. Example of Writing _DecimalT Class Template Constants to a File Using the ofstream Class
// write_num is passed an array. These values are // written to a text file with the fstream class. // If the function is successful a 0 is returned, otherwise a // negative value is returned (indicating an error). void write_num(_DecimalT<4,2> a[N]) { int i; ofstream outf("data",ios::trunc || ios::out, filebuf::openprot); if (!outf) { cerr << "Could not open file 'data' " <<endl; exit (EXIT_FAILURE); } for (i=0; i (lt) N; i++) { { outf << a[i]; } outf.close() } // read_num is passed an array. The values are // read from a text file with the fstream class. // If the function is successful a 0 is returned, otherwise a // negative value is returned (indicating an error). void read_num(_DecimalT<4,2> b[N]) { int i; ifstream file("data"); if (!file) { cerr << "Could not open file 'data' " <<endl; exit (EXIT_FAILURE); } for (i=0; i<N; i++) { file >> b[i]; cout << "b["<< i <<"]=" <<b[i]; <<endl; } if (file.eof()) { cerr << "Unexpected EOF!" <<endl; exit (EXIT_FAILURE); } file.close(); } |
The output is:
+--------------------------------------------------------------------------------+ |b[0]=12.35 | |b[1]=25.00 | |b[2]=-19.58 | +--------------------------------------------------------------------------------+
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.