/* testfile3.cpp CIS 150 6/2/2005 David Klick This program demonstrates the use of a repetition construct to read a file of unknown length. */ #include #include using std::cout; using std::ofstream; using std::ifstream; int main(void) { int n; // open a file for writing cout << "Opening output file\n"; ofstream outfile("datafile3.txt"); // display error and exit if file didn't open if (!outfile) { cout << "Error: could not open output file.\n"; return 1; } // write some data out to file cout << "Writing data to file\n"; for (n=11; n<40; n=n+2) { outfile << n << '\n'; } // done processing - close file outfile.close(); cout << "File created\n"; // open the file we created for reading cout << "Opening input file\n"; ifstream infile("datafile3.txt"); // display error and exit if file didn't open if (!infile) { cout << "Error: could not open input file.\n"; return 2; } // read all data from the file and display it // - a loop is used here because the number of // records to be read is unknown // - notice the use of a priming read cout << "Reading data from file\n"; infile >> n; while (!infile.eof()) { cout << n << '\n'; infile >> n; } // done processing - close file infile.close(); cout << "Program done\n"; return 0; }