Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005.

Similar presentations

Presentation on theme: "Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005."— Presentation transcript:

1 Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005

2 Slide: 2 Topics Classes in C++ Stream I/O library Defining custom input, output functions for user defined types File Input/Output Input/Output using String Stream

3 Slide: 3 Streams Stream I/O library Type-safe Extensible output to output stream object: cout << Exit program? ; cerr << Error encountered\n; input from input stream object: char answer [ 10 ] ; cin >> answer ; cin, cout and cerr are static objects defined in the library.

4 Slide: 4 Stream Library Classes ios istreamostream iostream fstream ifstreamofstreamistrstreamostrstream strstream

5 Slide: 5 Class ios class ios { public :... enum io_state { goodbit=0, eofbit=1, failbit=2, badbit=4, hardfail=0200 }; int eof () const; int fail () const; int bad () const; int good () const; int rdstate () const; void clear (int i = 0); operator void* (); int operator! () cost;... enum open_mode {in=1, out=2, ate=4, app=010, trunc=020 nocreate=040, noreplace=0100 }; enum seek_dir { beg=0, cur=1, end=2 };... };

6 Slide: 6 class ostream class ostream : virtual public ios { public :... ostream & operator<<(unsigned char c); ostream & operator<< (const char*); ostream & operator<< (int a); ostream& operator<<(double); ostream& operator<<(float); ostream& operator<<(unsigned int a); ostream& operator<<(void*); ostream& operator<<(short I);... ostream& put (char c);.. ostream& seekp (streampos p) ; streampos tellp (); ostream& flush (ostream&); }; Class ostream is defined with the operator<< to deal with built in types. operator<< function return a reference to the ostream it was called for. Cout<< x== << x;

7 Slide: 7 Built-in Type Output: Example /* use_ostream.cpp */ #include int main (int. char * [ ] ) { cout << 42; cout << \thello world\n; cout << ; double a = 4.56; int b = 7; cout << \nthe sum of << a << and << b << is: << a + b <<.\n; if (cout.good () ) { cout << all I/O successful.\n; } else { cerr << Some I/O operations failed.\n; } return 0; }

8 Slide: 8 class istream class istream : virtual public ios { public : istream& operator>> (char*); istream& operator>> (unsigned char*); istream& operator>> (unsigned char& c); istream& operator>> (char& C); istream operator>> (short&); istream& operator>> (int&); istream& operator>> (unsigned short&); isteam& operator>> (unsigned int&); istream& operator>> (unsigned long&); istream& operator>> (double&); ….. istream& get (char*, int lim, char delim+\n); istream& get (char&c); int get (); int peek ();... istrem& seekg (streampos p); Streampos tellg (); …. Input is similar to output. operator>> is overloaded in istream class to take care of built in types. operator>> returns a reference to the same istream object it was called for.

9 Slide: 9 Built in Types: Input #include int main (int, char * [ ] ) { int i; char buffer [ 256]; double d; cout << Enter an integer, a string, and a double\n cin >> I; // operator>> (int &); cin >> buffer;// operator>> (char *); cin >> d; // operator>> (double &); // cin >> i >> buffer >> d; is equivalent to above if (cin) { cout << int is: << i) << \nstring is: << buffer << \ndouble is: << d << \n; else { cerr << input unsuccessful. \n; } return 0; }

10 Slide: 10 Adding I/O operations to Complex Class class Complex{ double re, im; public: friend Complex operator + (Complex, Complex); friend Complex operator - (Complex, Complex); …. friend ostream& operator<< (ostream&, Complex); friend istream& operator>> (istream&, Complex); }; ostream &operator<< (ostream &s, Complex z) { return s<< ( << <<, << << ) ; } /* Input Formats permitted f ( f ) ( f, f ) */ istream &operator>> (ostream &s, Complex a) { double re =0, im = 0; char c = 0; s >>c; if (c == (){ s >> re >> c; if (c ==,) s >> im >> c; if (c != )) s. clear(ios::badbit); } else { s.putback©; s >> re; } if (s) a = Complex (re, im); return s; }

11 Slide: 11 File Stream Objects and Methods To store and retrieve data A file, a file stream object, a mode Data file Collection of data stored on a storage medium other than computer memory External file name File stream One way transmission path between the device file and the C++ program Mode Determines the data direction in the transmission stream

12 Slide: 12 File Stream Methods Pre-written methods Open, close, read, append, decide if EOF Open Open and establish link between the file and C++ program External computer name = stream object name used by the program; Both, ifstream and ofstream, can open an external file

13 Slide: 13 Input and Output Streams When an existing file is connected to an input file stream Data is made available for input starting at the first data item in the file When a file is connected to an output file stream Creates a new file and makes the file available for output If a file exists with the same name, old file is ERASED and all data is lost Can be fixed by indicator modes ios::app, ios::noreplace

14 Slide: 14 Opening Status When a file is opened Check if the connection is made Otherwise, crash will follow later ifstream inFile;,ios::nocreate); if( { cout << The file was not successfully opened. Check if file exists.\n; exit(1); } If file does not exist, open fails returns 1

15 Slide: 15 Mode Indicators If file exists, open for output filesios::noreplace If file does not exist, open failsios::nocreate Delete file contents if it existsios::trunc Open in binary mode (default text)ios::binary Go to the end of the opened fileios::ate Open in append modeios::app Open in output modeios::out Open in input modeios::in Methods/functions under ios class

16 Slide: 16 Another way to open When a file is opened Check if the connection is made Otherwise, crash will follow later fstream inFile;, ios::in | ios::nocreate); if( { cout << The file was not successfully opened. Check if file exists.\n; exit(1); } Use fstream class Requires indicator arguments

17 Slide: 17 fstream Methods Skip next n charsignore(n) If end of fileeof() Push char back to input stream putback(char-expression) Put char in out streamput(char-expression) Retrieve char without extracting peek(char-var) Extract charsgetline(string-var,n,\n) Extract next charget(char-var) MeaningMethod

18 Slide: 18 Reading From a File: Example #include void main() { char filename[MAXLENGTH] = test.dat; char descrip[MAXCHARS]; int ch; float price; ifstream inFile;, ios::nocreate); if ( { cout << \n The file was not successfully opened\n; exit(1); } cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2); while ( ( ch = inFile.peek()) != EOF) // check next character inFile >> descrip >> price; inFile.close(); }

19 Slide: 19 Random File Access File organization The way data is stored in a file Sequential organization Characters are stored in a sequential manner File access The way data is retrieved from the file Storing sequentially does not mean accessing sequentially Random access Any character can be read directly without having to read all the characters ahead of it Each ifstream object uses a position marker Keeps track of the offset of the next character from the beginning of the file

20 Slide: 20 File Position Marker Functions End of the fileios:: end Current positionios:: cur Beginningios:: beg Output, return current offsettellp(void) Input, return current offsettellg(void) Output, move to the offsetseekp(offset, mode) Input, move to the offsetseekg(offset, mode) MeaningName

21 Slide: 21 Examples Offset Positive offset means move forward in the file Negative offset means move backward in the file inFile.seekg(4L,ios::beg) // go to 5 th character in the input file (starts from 0 as // the first character) outFile.seekp(4L,ios::beg) inFile.seekg(4L,ios::cur) outFile.seekp(4L,ios::cur) inFile.tellg()

22 Slide: 22 Program #include Void main() { long offset, last; char ch; ifstream inFile(test.dat); if( { // Report error and exit } inFile.seekg(0L,ios::end); // move to the end of file (mark the offset) last = inFile.tellg(); // save the offset of the last char (return current offset) for ( offset = 1L; offset < last; offset++) { inFile.seekg(-offset, ios::end); // reverse access ch = inFile.get(); cout << ch << :; } inFile.close(); }

23 Slide: 23 File Streams as Function Arguments File stream objects can be passed as function arguments Formal parameter should be a reference to the appropriate stream ifstream& or ofstream&

24 Slide: 24 Program #include const int MAXLENGTH = 31; char filename[MAXLENGTH] = test.dat; void inOut(ofstream&); // function prototype void main() { ofstream outFile;; if( { // Report error and exit } inOut(outFile); // call the function } Pass the object reference

25 Slide: 25 Program void inOut(ofstream& fileOut) { const int LINELEN = 80; const int NUMLINES = 5; int count; char line[LINELEN]; cout << Please enter five lines of text: << endl; for(count = 0; count < NUMLINES; count++) { cin.getline(line, LINELEN, \n); fileOut << line << endl; } return; } Write on the outFile Stream file passed as reference

26 Slide: 26 Program #include int getOpen(ofstream&); void inOut(ofstream&); void main() { ofstream outFile; getOpen(outFile); // open the file inOut(outFile); // call the function }

27 Slide: 27 Program int getOpen(ofstream& fileOut) { const int MAXCHARS = 13; char name[MAXCHARS]; cout << Enter a file name : ; cin.getline(name,MAXCHARS,\n);; // open the file if( { cout << The file was not opened successfully << endl; exit(1); } return 0; }

28 Slide: 28 Writing to a String Stream #include using namespace std; void WriteHTMLPage(ostream & stream) { stream " << endl; stream CS 240 " << endl; stream " << endl; stream Welcome to CS 240! " << endl; stream " << endl; } int main() { ostrstream stream; WriteHTMLPage(stream); stream << ends; // writes '\0' to the stream cout << stream.str(); }

29 Slide: 29 Reading Words From a String Stream #include int main(int argc, char * argv[]) { istrstream stream(argv[1]); int count = 0; while (true) { string word; stream >> word; if (stream) ++count; else break; } cout << count << " words" << endl; return 0; }

Download ppt "Slide: 1 Interra Induction Training Object Oriented Programming in C++ IO Streams Kolkata, July 25, 2005."

Similar presentations

Ads by Google