// File: io6.C // // File I/O #include #include // for ifstream, ofstream, etc #include // for endl, setw(), etc #include // for INT_MAX constant, etc #include // for exit(), etc #define BUFLEN 33 typedef char buffer[BUFLEN] ; main() { buffer fname ; ifstream ifile ; int n = 0, data, *A ; // Get filename // cout << "Enter a filename: " ; cin >> setw(BUFLEN) >> fname ; cin.ignore(INT_MAX, '\n') ; ifile.open(fname) ; if (ifile == NULL) { cerr << "Could not open file: " << fname << endl ; exit(1) ; } // Read in an array of integers. First number is // the size of the array. // ifile >> n ; if (!ifile.good()) { cerr << "Could not find array size. Bye!" << endl ; exit(1) ; } A = new int[n] ; if (A == NULL) { cerr << "Out of memory! Bye!" << endl ; exit(1) ; } int i = 0 ; while (true) { ifile >> data ; if (ifile.eof()) { if (i == n) break ; cerr << "File is short! Bye!" << endl ; exit(1) ; } if (!ifile.good()) { cerr << "Bad data format! Bye!" << endl ; exit(1) ; } if (i >= n) { cerr << "File is long! Bye!" << endl ; exit(1) ; } A[i] = data ; i++ ; } ifile.close() ; ofstream ofile ; ofile.open("dump") ; if (ofile == NULL) { cerr << "Could not open output file!" << endl ; exit(1) ; } for (i = 0 ; i < n ; i++) { ofile << "A[" << i << "] = " << A[i] << endl ; } ofile.close() ; }