/* Test File I/O (TestFileIO.cpp) Read all the integers from an input file and write the average to an output file */ #include #include // file stream #include using namespace std; int main() { ifstream fin; // Input stream ofstream fout; // Output stream // Try opening the input file fin.open("in.txt"); if (!fin.is_open()) { cerr << "error: open input file failed" << endl; abort(); // Abnormally terminate the program (in ) } int sum = 0, number, count = 0; while (!(fin.eof())) { // Use >> to read fin >> number; sum += number; ++count; } double average = double(sum) / count; cout << "Count = " << count << " average = " << average << endl; fin.close(); // Try opening the output file fout.open("out.txt"); if (!fout.is_open()) { cerr << "error: open output file failed" << endl; abort(); } // Write the average to the output file using << fout << average; fout.close(); return 0; }