/* testfile1.cpp CIS 150 6/3/2008 David Klick This program demonstrates some simple file I/O techniques. This program doesn't work properly. */ #include #include using std::cout; using std::cin; using std::ofstream; using std::ifstream; void cont(); int main() { // 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"; cout << "n = " << n << '\n'; cout << "flag = " << flag << '\n'; cout << "x = " << x << '\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"; cont(); return 0; } void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample run: Opening output file Writing data to file: n = 17 flag = 1 x = 37.887 File created Opening input file Reading data from file n = 17137 flag = 1 x = 37.887 Program done Press enter to continue... */