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

Slides:



Advertisements
Similar presentations
Chapter 10 Input/Output Streams
Advertisements

1 Engineering Problem Solving With C++ An Object Based Approach Chapter 4 Programming with Data Files.
1 Lecture 31 Handling Selected Topics Again!! File I/O Special Lectures.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files (Review) * A computer file n is stored secondary storage devices (hard drive, CD) n can.
File I/O. COMP104 File I/O / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
Chapter 15.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Working with Data Files.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Program Input and the Software Design Process ROBERT REAVES.
計算機程式語言 Lecture 8-1 國立臺灣大學生物機電系 8 8 I/O File Streams and Data Files.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
1 CS161 Introduction to Computer Science Topic #13.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
1 I/O  C++ has no built-in support for input/output input/output is a library (iostream)  C++ program views input and output as a stream of bytes  Input:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
1 CSC241: Object Oriented Programming Lecture No 32.
Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 4 Working with Data Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Learners Support Publications Working with Files.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Lecture 14 Arguments, Classes and Files. Arguments.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Computer Programming II Lecture 9. Files Processing - We have been using the iostream standard library, which provides cin and cout methods for reading.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
ifstreams and ofstreams
Introduction to Programming
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Parallel Arrays Parallel array =>Two or more arrays with the same number of elements used for storing related information about a collection of data. Example:
File I/O.
File I/O Streams, files, strings 1 1.
Lecture 5A File processing Richard Gesick.
Working with Data Files
Interactive I/O Input from keyboard Must prompt user User friendly
Basic File I/O and Stream Objects
IO Overview CSCE 121 J. Michael Moore
Programming with Data Files
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Standard Input/Output Stream
File I/O in C++ I.
CS150 Introduction to Computer Science 1
File I/O.
CHAPTER 4 File Processing.
Reading from and Writing to Files
ifstreams and ofstreams
C++ for Engineers and Scientists Second Edition
IO Overview CSCE 121 Strongly influenced by slides created by Bjarne Stroustrup and Jennifer Welch.
Stream States CSCE 121 Based on slides created by Carlos Soto.
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

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

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

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.

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

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

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;

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

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.

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

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<< ( << z.re <<, << z.im << ) ; } /* 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; }

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

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 inFile.open(test.data); Both, ifstream and ofstream, can open an external file

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

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

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

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

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

Slide: 18 Reading From a File: Example #include void main() { char filename[MAXLENGTH] = test.dat; char descrip[MAXCHARS]; int ch; float price; ifstream inFile; inFile.open(filename, ios::nocreate); if (inFile.fail()) { 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(); }

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

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

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()

Slide: 22 Program #include Void main() { long offset, last; char ch; ifstream inFile(test.dat); if(inFile.fail()) { // 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(); }

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&

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

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

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

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

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

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