c++ files

             
Files can provide input to a program much faster than input provided by a person. Programs can also output to files where data can be permanently stored or used as input to another program.


.. setting up a stream and opening a file

File Input/Output ================= File I/O 1. Include fstream header (#include <fstream>) 2. Declare file stream variables (ifstream OR ofstream) 3. Associate the file stream variables with the I/O sources (open) 4. Use the file stream variables with >>, <<, or other I/O functions 5. Close the filesFile Input/Output
Disk I/O Stream =============== like cin, cout stream >>, << and manipulators ok Input ===== Statements for Using Disk I/O: Input #include <fstream> ifstream myInfile; // declare new stream myInfile.open("myIn.dat"); // open file and associate with stream // READ DATA HERE myInfile >> num1 >> num2; // READ DATA! myInfile.close( ); // close files
NOTE: ===== ifstream myInfile; // declare new stream myInfile.open("myIn.dat"); // open file and associate with stream can be replaced by ifstream myInfile("myIn.dat"); // declare new sream AND open file
Output ====== Statements for Using Disk I/O: Output #include <fstream> ofstream myOutfile; // declarations int num1, num2; myOutfile.open("myOut.dat"); // open files // WRITE DATA HERE myOutfile << num1 * 2 << endl; // WRITE INFO myOutfile.close( ); // close files
What Does Opening a File Do? ============================ Associates C++ stream identifier with physical (disk) file Places file reading marker at beginning of the file, Input Files - if the input file does not exist on disk, open is not successful Output Files - if the output file does not exist on disk, a new file with that name is created - if the output file already exists, it is erased Stream Fail State ================= When stream enters fail state, further I/O ops have no effect No error message Reasons for entering fail state: - invalid input data (often the wrong type) - opening an input file that doesn’t exist - opening an output file on a diskette that is full or write-protected - end of file! Stream identifier is set to 0
Checking on the State of I/O Stream ifstream myInfile; // open the data file myInfile.open ("data.dat"); // priming read myInfile >> somedata; // while not at end of file while (!myInfile.eof()) // while (myInfile != 0) { cout << somedata; // write to screen myInfile >> somedata; // get next record } ... myInfile.close();

.. using the wyatt data files on jupiter

Data Files (ASCII) ================== Files are located at: web address http://jupiter.clarion.edu/~wyatt/!Data c++ file address /export/home/wyatt/public_html/!Data/filename.ext
To use a data file directly from the site Use full pathname /export/home/wyatt/public_html/!Data/salary.txt
So, for a new data stream called "fin": To read TWO values from this file: ifstream fin ("/export/home/wyatt/public_html/!Data/salary.txt"); double num1, num2; // make sure to use the correct type!! fin >> num1 >> num2;

.. looping through a file

... // 1. file stream library #include <fstream> ... // 2. declare variable for input stream ifstream fin; ... // 3. open file fin.open("data.dat"); /////////////////////////////////////////////////////// // ASSUME: each record of the file has one integer, age // and one string, firstName /////////////////////////////////////////////////////// // 4a. read from file: primimg read fin >> age >> firstName; // read first record from file do // do 1 or more times { // process the record: // may do calculations or output or whatever is needed // to transform the input into information to be output // 4b. read from file: get next record (if any) from file fin >> age >> firstName; // read some integer into variable x } while (!fin.eof()); // read until end of file ... // 5. close file fin.close();
OR.. could use while instead of do while
// 1. file stream library #include <fstream> ... // 2,3. declare variable for input stream AND open ifstream fileIn ("data.dat"); ... // 4a. read from file: primimg read fileIn >> age >> firstName; // read first record from file while(!fileIn.eof()) // do zero or more times { // process the record: // may do calculations or output or whatever is needed // to transform the input into information to be output // 4b. read from file: get remaining values from file in a loop fileIn >> age >> firstName; // read first record from file } ... // 5. close file fileIn.close();

.. getline( ): reading ALL characters including whitespace

Reading Data ============ To read data into a string >> skips leading whitespace, reads ANY character(s) until whitespace Reading stops on whitespace can NOT be used to read strings with blanks
Reading strings that include whitespace ======================================== getline() - reads entire line WITH spaces ========= reads until end of the current line (reads blanks too) getline function has 2 arguments 1. input stream variable 2. string variable string message ; cin >> message; // old way for no spaces getline(cin, message); // new way w/spaces

ifstream in; in.open("data.dat"); // read ENTIRE first record (line) from file including spaces! getline(in, mystring); // output the entire line just read cout << mystring << endl; // output length of string cout << mystring.length() << endl; -------------------------------------------------- getline() operation -------------------- getline reads leading whitespace characters (blanks and newlines) getline reads successive characters (including blanks) into string getline stops when it reaches newline character '\n' '\n' is consumed, but is NOT stored into the string variable
getline() reading an ENTIRE name ================================ #include <string> #include <iostream> using namespace std; int main() { ifstream in; string fullName; cout << "What is your FULL name? "; getline(cin, fullName); cout << "Hello " << fullName << "\n"; return 0; }
getline() used when finding a word in a string ============================================== // find a word within a string #include <string> #include <fstream> #include <iostream> using namespace std; int main() { ifstream in; string s1, s2; int pos, len; ... in.open("data.dat"); cout << "Enter a word: "; // boy cin >> s2; getline(in, s1); // "The boy walks fast" pos = s1.find(s2); // pos = 4 len = s1.length(); // len = 18 len = s2.length(); // len = 3 pos = s1.find(s2, 7); // starts lookng at position 7 ^^^ cout << s1 << endl << s2 << endl << pos << endl << len << endl; return 0; }
getline() in a loop =================== // read a file a line at a time // and print it out line by line #include <string> #include <fstream> #include <iostream> using namespace std; int main() { ifstream in; string lineOfText; in.open("data.dat"); getline(in, lineOfText); while (!in.eof()) { cout << lineOfText << endl; getline(in, lineOfText); } return 0; }

.. I/O manipulators

I/O Manipulators: 2 types ================== Nonparameterized: <iostream> endl moves cursor to next line fixed will not use scientific notation scientific use scientific showpoint even for 0, show decinmal point noshowpoint left justify for setw right justify Parameterized: <iomanip> setw(n) specifies fieldwidth affects ONLY THE VERY NEXT item displayed default is right-justified setprecision(n) rounds # places right of decimal point setfill('x') determines character used for "extra" spaces in setw default is blank
Code example: double x = 92.75648; cout << fixed << showpoint << setprecision(2); cout << setw(8) << x << endl; 92.76 123456789012345 cout << setw(12) << x << endl; 92.76 123456789012345 cout << setprecision(4) << setw(12) << x << endl; 92.7565 123456789012345 cout << setprecision(4) << setfill('-') << setw(12) << x << endl; -----92.7565 123456789012345
Other uppercase, nouppercase, dec, oct, hex, setbase(8|10|16), showbase, noshowbase, showpos, noshowpos, flush , skipws, noskipws
#include <iostream> #include <iomanip> using namespace std; int main() { const float tenth = 0.1; const float one = 1.0; const float big = 1234567890.0; cout << "A. " << tenth << ", " << one << ", " << big << endl; cout << "B. " << fixed << tenth << ", " << one << ", " << big << endl; cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl; cout << "D. " << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl; cout << "E. " << setprecision(20) << tenth << endl; cout << "F. " << setw(8) << setfill('*') << 34 << 45 << endl; cout << "G. " << setw(8) << 34 << setw(8) << 45 << endl; return 0; } Output: A. 0.1, 1, 1.23457e+09 B. 0.100000, 1.000000, 1234567936.000000 C. 1.000000e-01, 1.000000e+00, 1.234568e+09 D. 0.100, 1.000, 1234567936.000 E. 0.10000000149011611938 F. ******3445 G. ******34******45
#include <iostream> //Example: left justification #include <iomanip> using namespace std; int main() { int x = 15, y = 7634; cout << left; cout << "12345678901234567890" << endl; cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; cout << setfill('*'); cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; cout << setw(5) << x << setw(7) << setfill('#') << y << setw(8) << "Warm" << endl; cout << setw(5) << setfill('@') << x << setw(7) << setfill('#') << y << setw(8) << setfill('^') << "Warm" << endl; cout << right; cout << setfill(' '); cout << setw(5) << x << setw(7) << y << setw(8) << "Warm" << endl; return 0; } 12345678901234567890 15 7634 Warm 15***7634***Warm**** 15***7634###Warm#### 15@@@7634###Warm^^^^ 15 7634 Warm