CSCI26I File I/O in Detail ? Review Programs can read and write - - PowerPoint PPT Presentation

csci26i
SMART_READER_LITE
LIVE PREVIEW

CSCI26I File I/O in Detail ? Review Programs can read and write - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

CSCI26I

File I/O in Detail

slide-2
SLIDE 2

?

slide-3
SLIDE 3

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
slide-4
SLIDE 4

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
slide-5
SLIDE 5

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; }

slide-6
SLIDE 6

Reading Data from Streams

Variable types matter! Values in the file matter!

slide-7
SLIDE 7

Example

1 2 200 300 1.1 2.1 x cc 320 420

datafile.txt

int main() { int x, y; ifstream data("data.txt"); while (data >> x >> y) { cout << x << " " << y << endl; } data.close(); system("PAUSE"); return 0; }

slide-8
SLIDE 8

How >> and Streams Work

First, remember to think of this data “streaming” to your program.

1 2 200 300 320 420

datafile.txt

slide-9
SLIDE 9

How >> and Streams Work

420 320 300 200 2 1

ifstream numbaz(“datafile.txt”);

1 2 200 300 320 420

datafile.txt

slide-10
SLIDE 10

How >> and Streams Work

420 320 300 200 2 1

numbaz int x; while (numbaz >> x) { // have fun }

cursor

“Computer, read the next numeric characters after the cursor up until a whitespace character and assuming it’s numeric, assign the value to x.”

slide-11
SLIDE 11

How >> and Streams Work

420 320 300 200 2 1

numbaz int x; while (numbaz >> x) { // have fun }

cursor

“Computer, read the next numeric characters after the cursor up until a whitespace character and assuming it’s numeric, assign the value to x.”

whee!

slide-12
SLIDE 12

Writing Files

  • fstream myoutput(“filename.ext”);

“Computer, create an output filestream called myoutput and save its contents to filename.ext.”

slide-13
SLIDE 13
  • fstream myoutput(“filename.ext”);

myoutput << “obladee obladah life goes on”; myoutput.close();

Use It Like cout

cout << “i am the walrus”;

“Computer, push this string to the screen.” “Computer, push this string to my file.”

slide-14
SLIDE 14

Homework

  • Read Etter p144 - 145 and 4.5
  • Complete assignment 12_shiftCipher

Mmmmoooooooooo!