CSCI26I File I/O in Detail
?
Review • Programs can read and write files to disk • And from any “stream” ! • #include <fstream> • ifstream my_file_object(“filename.ext”) • Use while loops to repeatedly read from the stream • close() all filestreams
You Will Always... • Include the fstream library • Declare your filestreams (and open them) • Check for an I/O error • While not at the end of file, do stuff • Close the file
I/O Boilerplate #include <cstdlib> #include <iostream> #include <fstream> using namespace std; int main() { char x; // or int x, double x, etc. ifstream mydata("FILENAME"); if(!mydata) { � cerr << "Error" << endl; � system("PAUSE"); � exit(1); } while(myfile >> x) { // do marvelous things } myfile.close(); return 0; }
Reading Data from Streams Variable types matter! Values in the file matter!
Example int main() datafile.txt { int x, y; 1 2 ifstream data("data.txt"); 200 300 while (data >> x >> y) { 1.1 2.1 cout << x << " " << y << endl; } x cc data.close(); 320 420 system("PAUSE"); return 0; }
How >> and Streams Work datafile.txt First, remember to think of this data 1 2 “streaming” to your program. 200 300 320 420
How >> and Streams Work datafile.txt ifstream numbaz(“datafile.txt”); 1 2 420 320 300 200 2 1 200 300 320 420
How >> and Streams Work cursor int x; while (numbaz >> x) { 420 320 300 200 2 1 // have fun } numbaz “Computer, read the next numeric characters after the cursor up until a whitespace character and assuming it’s numeric, assign the value to x .”
How >> and Streams Work cursor int x; while (numbaz >> x) { 420 320 300 200 2 1 // have fun } numbaz whee! “Computer, read the next numeric characters after the cursor up until a whitespace character and assuming it’s numeric, assign the value to x .”
Writing Files ofstream myoutput(“filename.ext”); “Computer, create an output filestream called myoutput and save its contents to filename.ext .”
Use It Like cout cout << “i am the walrus”; “Computer, push this string to the screen.” ofstream myoutput(“filename.ext”); myoutput << “obladee obladah life goes on”; myoutput.close(); “Computer, push this string to my file.”
Homework • Read Etter p144 - 145 and 4.5 • Complete assignment 12_shiftCipher Mmmmoooooooooo!
Recommend
More recommend