34
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Embed Size (px)

Citation preview

Page 1: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

CSIS 123A Lecture 8

Streams & File IO

Glenn Stevenson CSIS 113A MSJC

Page 2: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Introduction

Streams Special objects Deliver program input and output

File I/O Uses inheritance

Covered Later

File I/O very useful, so covered here

Glenn Stevenson CSIS 113A MSJC

Page 3: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Streams

A flow of characters Input stream

Flow into program Can come from keyboard Can come from file

Output stream Flow out of program

Can go to screen Can go to file

Glenn Stevenson CSIS 113A MSJC

Page 4: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Streams Usage

We’ve used streams already cin

Input stream object connected to keyboard

cout Output stream object connected to screen

Can define other streams To or from files Used similarly as cin, cout

Glenn Stevenson CSIS 113A MSJC

Page 5: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Streams Usage Like cin, cout

Consider: Given program defines stream inStream

that comes from some file:int theNumber;inStream >> theNumber; Reads value from stream, assigned to

theNumber

Program defines stream outStream that goesto some fileoutStream << “theNumber is “ << theNumber; Writes value to stream, which goes to fileGlenn Stevenson CSIS 113A

MSJC

Page 6: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Files

We’ll use text files Reading from file

When program takes input

Writing to file When program sends output

Start at beginning of file to end Other methods available We’ll discuss this simple text file access

hereGlenn Stevenson CSIS 113A

MSJC

Page 7: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

File Connection

Must first connect file to stream object For input:

File ifstream object

For output: File ofstream object

Classes ifstream and ofstream Defined in library <fstream> Named in std namespace

Glenn Stevenson CSIS 113A MSJC

Page 8: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

File I/O Libraries

To allow both file input and output in yourprogram:

#include <fstream>using namespace std;

OR#include <fstream>using std::ifstream;using std::ofstream;

Glenn Stevenson CSIS 113A MSJC

Page 9: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Declaring Streams

Stream must be declared like any otherclass variable:

ifstream inStream;ofstream outStream;

Must then ‘connect’ to file:inStream.open(“infile.txt”);

Called ‘opening the file’ Uses member function open Can specify complete pathname

Glenn Stevenson CSIS 113A MSJC

Page 10: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Streams Usage

Once declared use normally!int oneNumber, anotherNumber;inStream >> oneNumber >>

anotherNumber;

Output stream similar:ofstream outStream;outStream.open(“outfile.txt”);outStream << “oneNumber = “ <<

oneNumber<< “ anotherNumber = “<< anotherNumber;

Sends items to output fileGlenn Stevenson CSIS 113A

MSJC

Page 11: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

File Names

Programs and files Files have two names to our programs

External file name Also called ‘physical file name’ Like ‘infile.txt’ Sometimes considered ‘real file name’ Used only once in program (to open)

Stream name Also called ‘logical file name’ Program uses this name for all file activity

Glenn Stevenson CSIS 113A MSJC

Page 12: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Closing Files

Files should be closed When program completed getting input or

sending output Disconnects stream from file In action:

inStream.close();outStream.close();

Note no arguments

Files automatically close when programends

Glenn Stevenson CSIS 113A MSJC

Page 13: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

File Flush

Output often ‘buffered’ Temporarily stored before written to file Written in ‘groups’

Occasionally might need to force writing:outStream.flush();

Member function flush, for all output streams All buffered output is physically written

Closing file automatically calls flush()

Glenn Stevenson CSIS 113A MSJC

Page 14: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

File Example

Glenn Stevenson CSIS 113A MSJC

Page 15: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Appending to a File Standard open operation begins with

empty file Even if file exists contents lost

Open for append:ofstream outStream;outStream.open(“important.txt”, ios::app);

If file doesn’t exist creates it If file exists appends to end 2nd argument is class ios defined constant

In <iostream> library, std namespaceGlenn Stevenson CSIS 113A

MSJC

Page 16: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Alternative Syntax for File Opens

Can specify filename at declaration Passed as argument to constructor

ifstream inStream;inStream.open(“infile.txt”);

EQUIVALENT TO:

ifstream inStream(“infile.txt”);

Glenn Stevenson CSIS 113A MSJC

Page 17: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Checking File Open Success File opens could fail

If input file doesn’t exist No write permissions to output file Unexpected results

Member function fail() Place call to fail() to check stream operation

successinStream.open(“stuff.txt”);if (inStream.fail()){

cout << “File open failed.\n”;exit(1);

}Glenn Stevenson CSIS 113A

MSJC

Page 18: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Character I/O with Files

All cin and cout character I/O same forfiles!

Member functions work same: get, getline put, putback, peek, ignore

Glenn Stevenson CSIS 113A MSJC

Page 19: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Checking End of File Use loop to process file until end

Typical approach

Two ways to test for end of file Member function eof()

inStream.get(next);while (!inStream.eof()){

cout << next;inStream.get(next);

} Reads each character until file ends eof() member function returns bool

Glenn Stevenson CSIS 113A MSJC

Page 20: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

End of File Check with Read

Second method read operation returns bool value!

(inStream >> next) Expression returns true if read successful Returns false if attempt to read beyond end of file

In action:double next, sum = 0;while (inStream >> next)

sum = sum + next;cout << “the sum is “ << sum << endl;

Glenn Stevenson CSIS 113A MSJC

Page 21: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Random Access to Files

Sequential Access Most commonly used

Random Access Rapid access to records Perhaps very large database Access ‘randomly’ to any part of file Use fstream objects

input and output

Glenn Stevenson CSIS 113A MSJC

Page 22: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Random Access Tools Opens same as istream or ostream

Adds second argument fstream rwStream;

rwStream.open(“stuff”, ios::in | ios:: out); Opens with read and write capability

Move about in file rwStream.seekp(1000);

Positions put-pointer at 1000th byte

rwStream.seekg(1000); Positions get-pointer at 1000th byte

Glenn Stevenson CSIS 113A MSJC

Page 23: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Random Access Sizes

To move about must know sizes sizeof() operator determines number of

bytesrequired for an object:sizeof(s) //Where s is string s = “Hello”sizeof(10)sizeof(double)sizeof(myObject)

Position put-pointer at 100th record of objects:

rwStream.seekp(100*sizeof(myObject) – 1);Glenn Stevenson CSIS 113A MSJC

Page 24: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

More seekp, seekg• ostream&  seekp ( streampos pos );

– move the file pointer to a specific offset from where it currently is

• ostream&  seekp ( streamoff off , ios_base::seekdir dir ); – allows you to specify a base point to offset from one of

the following• ios_base::beg seek relative to beginning of file • ios_base::end seek relative to end of file • ios_base::cur seek relative to current position

Glenn Stevenson CSIS 113A MSJC

Page 25: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

tellp tellg

• Similar to seekp and seekg– Except they return the current position in the

file.

• tellp is part of ostream

• tellg is part of istream

Glenn Stevenson CSIS 113A MSJC

Page 26: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Bitwise operators

• & - bitwise AND

• | - bitwise OR

• ^ - bitwise XOR

• ~ - ones compliment

• << - left shift

• >> - right shift

Page 27: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Bitwise AND &• In order for result to be one both bits must

be 1:1 & 1 = 1

1 & 0 = 0

0 & 1 = 0

0 & 0 = 0

• An Example – int x = 7 , y = 3;

int z = x & y; // z = 301110011---------0011

Page 28: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Bitwise OR |• In order for result to be one either bit must

be 1:1 | 1 = 1

1 | 0 = 1

0 | 1 = 1

0 | 0 = 0

• Can be used for adding. – Take previous example x | y // 7 | 3

01110011--------- // result is 7! 0111

Page 29: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Bitwise XOR ^ operator

• Returns 1 if one of the values is 1 but not both:

1 ^ 1 = 0

1 ^ 0 = 1

0 ^ 1 = 1

0 ^ 0 = 0

01110011--------- // result is 4!0100

Page 30: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

More XOR • Used perfectly to toggle a bit

– Suppose you want a function that will toggle bit 3 on or off.

• Create a mask :» 0001000

• XOR your bits with the mask:int mask = 8;int bitPattern = 170; //10101010

bitPattern^=mask;

Page 31: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

XOR Toggle result• First time toggle results

1010101000001000--------------10100010

bitPattern now holds 162

• XOR again1010001000001000--------------10101010

bitPattern now holds 170

Page 32: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

~ Ones Compliment

• Simply flips all bits – Ones to zeros, zeros to ones

int x = 3; // 011x = ~x;; // 11111111100

• Combine it with the & operator to ensure a bit is off!

int b = 50;int c = b & ~0x10;

00110010 - b & 11101111 - ~0x10 ---------- 00100010 - result

Page 33: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Left Shift << operator

• Shifts bits to the left – Essentially multiplying the number by 2

int x = 4;

x = x << 1;

100 // binary x = 4

After shift

x = 1000; // binary x or 8

Page 34: CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC

Right Shift >> Operator

• Works same as left except moves bits to the right. Essentially divides number by 2

int x = 4;

x = x >> 1; // x now becomes 2