1 CS 105 Lecture 9 Files Version of Mon, Mar 28, 2011, 3:13 pm
2 Files Data in main memory is “volatile” File: Place for “permanent” data storage C: drive, A: drive, flash drive, etc. In C++, files can be read different ways Stream input (or output) lets us read (or write) a sequence of data. We also use streams (cin, cout) to model keyboard input and text output.
3 In C++, the programmer can declare output streams and link them to output files. Output File Streams #include using namespace std;.... int num1, num2, num3; cout << "Enter 3 numbers for datafile: "; cin >> num1 >> num2 >> num3; ofstream outputStream; outputStream.open("datafile.txt"); outputStream << num1 << " "; outputStream << num2 << " "; outputStream << num3 << endl; outputStream.close();
4 In C++, the programmer can declare input streams and link them to input files. Input File Streams #include using namespace std;.... int num1, num2, num3; ifstream inputStream; inputStream.open("datafile.txt"); inputStream >> num1 >> num2 >> num3; inputStream.close();
5 To Read or Write from a File Declare the file stream object. I.e., give it a name. Associate a file name with the file stream object by opening the file. Read or write to the file using > operators. Close the file.
6 Manipulators Used to format output neatly: Left justification (columns of names) Right justification (columns of numbers) Minimum field length (padding) Decimal places For more information, Malik pgs There's also an older style of formatting that uses "printf" and "scanf" that has been copied into Java.
7 Example of Output Manipulation #include using namespace std; int main() { ifstream input; int loops, ival, i; float fval; string name; cout << showpoint << scientific; cout << setprecision(2); input.open("mydata.txt"); input >> loops; for (i=0; i < loops; i++) { input >> ival; input >> fval; input >> name; cout << right; cout << setw(4) << ival << " "; cout << setw(12) << fval << " "; cout << left; cout << setw(10) << name << endl; } return(0); } Output e+000 Jon e+001 Bill e+010 Mary e+000 Smith e+003 xyz
8 Example with File Input #include using namespace std; int main() { ifstream input; int loops, ival, i; float fval; string name; cout << showpoint << scientific << setprecision(2); input.open("mydata.txt"); input >> loops; for (i=0; i < loops; i++) { input >> ival; input >> fval; input >> name; cout << right; cout << setw(4) << ival << " "; cout << setw(12) << fval << " "; cout << left; cout << setw(10) << name << endl; } return(0); } mydata.txt file: Jon Bill e9 Mary Smith -3 -4e3 xyz Output: e+00 Jon e+01 Bill e+10 Mary e+00 Smith e+03 xyz