Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC."— Presentation transcript:

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

2 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

3 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

4 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

5 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 goes to some file outStream << “theNumber is “ << theNumber;  Writes value to stream, which goes to file Glenn Stevenson CSIS 113A MSJC

6 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 here Glenn Stevenson CSIS 113A MSJC

7 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  Named in std namespace Glenn Stevenson CSIS 113A MSJC

8 File I/O Libraries  To allow both file input and output in your program: #include using namespace std; OR #include using std::ifstream; using std::ofstream; Glenn Stevenson CSIS 113A MSJC

9 Declaring Streams  Stream must be declared like any other class 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

10 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 file Glenn Stevenson CSIS 113A MSJC

11 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

12 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 program ends Glenn Stevenson CSIS 113A MSJC

13 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

14 File Example Glenn Stevenson CSIS 113A MSJC

15 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  2 nd argument is class ios defined constant  In library, std namespace Glenn Stevenson CSIS 113A MSJC

16 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

17 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 success inStream.open(“stuff.txt”); if (inStream.fail()) { cout << “File open failed.\n”; exit(1); } Glenn Stevenson CSIS 113A MSJC

18 Character I/O with Files  All cin and cout character I/O same for files!  Member functions work same:  get, getline  put, putback,  peek, ignore Glenn Stevenson CSIS 113A MSJC

19 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

20 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

21 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

22 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 1000 th byte  rwStream.seekg(1000);  Positions get-pointer at 1000 th byte Glenn Stevenson CSIS 113A MSJC

23 Random Access Sizes  To move about  must know sizes  sizeof() operator determines number of bytes required for an object: sizeof(s)//Where s is string s = “Hello” sizeof(10) sizeof(double) sizeof(myObject)  Position put-pointer at 100 th record of objects: rwStream.seekp(100*sizeof(myObject) – 1); Glenn Stevenson CSIS 113A MSJC

24 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

25 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

26 Bitwise operators & - bitwise AND | - bitwise OR ^ - bitwise XOR ~ - ones compliment << - left shift >> - right shift

27 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 = 3 0111 0011 --------- 0011

28 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 0111 0011 --------- // result is 7! 0111

29 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 0111 0011 --------- // result is 4! 0100

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

31 XOR Toggle result First time toggle results 10101010 00001000 -------------- 10100010 bitPattern now holds 162 XOR again 10100010 00001000 -------------- 10101010 bitPattern now holds 170

32 ~ Ones Compliment Simply flips all bits –Ones to zeros, zeros to ones int x = 3; // 011 x = ~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

33 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

34 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


Download ppt "CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC."

Similar presentations


Ads by Google