/* testfile1.cpp CIS 150 6/2/2005 David Klick This program demonstrates some simple file I/O techniques. */ #include #include using std::cout; using std::ofstream; using std::ifstream; int main(void) { // create some data to write to file int n = 17; double x = 37.887; bool flag = true; // open a file for writing cout << "Opening output file\n"; ofstream outfile("datafile1.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 // - It should be noted that this won't actually work // properly because there is nothing separating the // fields when they are written. This program writes // the data fine, but we can't read it reliably. cout << "Writing data to file\n"; outfile << n << flag << x << '\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("datafile1.txt"); // display error and exit if file didn't open if (!infile) { cout << "Error: could not open input file.\n"; return 2; } // read some data from the file and display it // - As noted above, reading won't work properly. cout << "Reading data from file\n"; infile >> n >> flag >> x; cout << "n = " << n << '\n'; cout << "flag = " << flag << '\n'; cout << "x = " << x << '\n'; // done processing - close file infile.close(); cout << "Program done\n"; return 0; }