CS 3370.  Inserters and Extractors  Stream State  Files Streams  String Streams  Formatting  Manipulators  Internationalization.

Slides:



Advertisements
Similar presentations
IOStreams CNS 3370 Copyright 2003, Fresh Sources, Inc.
Advertisements

Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 12 Streams and File I/O. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  I/O Streams  File I/O  Character.
File I/O Finished off Colin Cherry standing in for Dr. Lin.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
The Standard String Class Is actually a template: –typedef basic_string string This means you can have strings of things other than chars.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
1 File I/O 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.
Chapter 3: Input/Output
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.
C++ Programming Certificate University of Washington Cliff Green
Sayed Ahmed Just E.T.C Technologies Inc. Just E.T.C. Education Inc.
1 Advanced Input and Output COSC1567 C++ Programming Lecture 9.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
CSE 232: C++ Input/Output Manipulation Built-In and Simple User Defined Types in C++ int, long, short, char (signed, integer division) –unsigned versions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
File I/O ifstreams and ofstreams Sections 11.1 &
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
C++ FILE I/O.
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.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
Student Book Input / Output in C++
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
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:
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring Fall 2016 Set 10: Input/Output Streams 1 Based on slides created.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Lecture 14 Arguments, Classes and Files. Arguments.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
CS212: Object Oriented Analysis and Design
Chapter 8 CS 3370 – C++ I/O Classes.
17 File Processing.
Chapter 13: Advanced File and I/O Operations
Basic Input and Output Operations
CISC/CMPE320 - Prof. McLeod
Standard Input/Output Streams
Standard Input/Output Streams
File I/O Streams, files, strings 1 1.
files Dr. Bhargavi Goswami Department of Computer Science
Programming with Data Files
Today’s Lecture I/O Streams Tools for File I/O
Chapter 13: Advanced File and I/O Operations
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Topics Input and Output Streams More Detailed Error Testing
ENERGY 211 / CME 211 Lecture 9 October 10, 2008.
File I/O in C++ II.
Input/Output Streams, Part 2
Presentation transcript:

CS 3370

 Inserters and Extractors  Stream State  Files Streams  String Streams  Formatting  Manipulators  Internationalization

 Insert an object into a stream  it does formatted output  Uses operator<<  the “left-shift” operator  the arrow suggests the direction of the data flow  Easy to define for your own classes

 A Date class inserter: ostream& operator<<(ostream& os, const Date& d) { char fillc = os.fill('0'); os << setw(2) << d.getMonth() << '-' << setw(2) << d.getDay() << '-' << setw(4) << d.getYear() << setfill(fillc); return os; }

istream& operator>>(istream& is, Date& d) { is >> d.month; char dash; is >> dash; if(dash != '-') { is.putback(dash); is.setstate(ios::failbit); // Input disabled return is; } is >> d.day; is >> dash; if(dash != '-') { is.putback(dash); is.setstate(ios::failbit); } is >> d.year; return is; }

 4 states:  eof: set upon an attempt to read past end-of-file ▪ sets fail automatically ▪ eof is meaningless for output streams  fail: an operation failed (e.g., alpha chars when reading int)  bad: stream is broken (no memory for buffer, device failure)  good: none of the other 3 states occurred  When an error occurs (fail or bad), the stream is disabled  All subsequent stream operations are ignored  Can re-enable stream operations with clear( )

 Can test with associated member functions:  good( ), eof( ), fail( ), bad( )  Can test for successful input like this:  if (strm)  same as if (!strm.fail( ) && !strm.bad() && ! strm.eof( ))  Can also use exceptions

 Can have exceptions thrown instead of checking state  Call the exceptions( ) member function  Can pick which states you want to throw: myStream.exceptions(ios::badbit);  The exception type thrown is ios::failure  ios is a base class for streams  See strmexcept.cpp

 while (myStream >> x) // process x (this assumes no input failure)  while (getline(myStream, line)) // process line (ditto)  You can check conditions separately  if (myStream.eof( )) …  if (myStream.fail( )) …

 get  getline  ignore  putback  unget  peek

 get( )  returns the next character, or -1  whitespace included  get(char& c)  puts the character read in c  returns the stream  get(char* s, int n, char delim = ‘\n’)  reads n characters or up to delim

 getline(char* s, int n, char delim = ‘\n’)  returns stream  reads and discards delim (different from get)  std namespace scope version  uses a string, not a char*  declared in  getline(istream& is, string& s, char delim = ‘\n’)  returns stream

 Discards characters  ignore(int n = 1, int delim = eof( ))  returns stream  For a large n, use:  std::numeric_limits ::max()

 unget()  Moves the stream’s get pointer back one  The next input op re-reads the previous character  putback(char)  Puts an arbitrary character into the buffer  So the next input op reads that character  peek()  Returns the next character without moving the get pointer beyond it

 Classes ifstream, ofstream, fstream  declared in  Constructors open, destructors close automatically  All normal stream operations apply  Additional member functions:  close( ), open( )  Open modes  ios::in, ios::out, ios::app, ios::ate, ios::trunc, ios::binary  Can combine with a bitwise-or ( | )

 Can move around in a stream  except when using the console, of course  Using functions seekp( ), seekg( )  seekp( ) seeks in the output buffer (p = “put”)  seekg( ) seeks in the input buffer (g = “get”)  Simultaneous I/O streams share the same buffer ▪ File streams keep the put/get pointers together ▪ In string streams they’re independent

 Often used by databases  can access records randomly  Fields must have only built-in data  numbers, C-style strings, static arrays  no pointers!  uses binary mode  Use the write and read member functions  See employeedb.cpp

 Classes istringstream, ostringstream, stringstream  declared in  Writes to or reads from a string  or both ▪ but remember the get/put pointers are independent  Useful for converting other data types to and from strings  Examples: C04/IString.cpp, C04/Ostring.cpp, C04/HTMLStripper2.cpp

 Can set stream attributes  width, fill character, alignment, numeric base, floating-point format, decimal precision, etc.  Use setf( ) and unsetf( )  Example: C04/Format.cpp

 The data area(s) held by the stream  One for input, one for output ▪ Streams that support both, have both  Can access via the function rdbuf( )  A “Way Station” for data en route  Usually don’t worry about it  One cool feature:  C04/SType.cpp, hexdec.cpp

 A shorthand for setting/unsetting stream attributes  dec, hex, endl, flush  Achieved via a special overload convention  manipulators are functions  when inserted, the following function is called: ostream& ostream::operator<<(ostream& (*pf)(ostream&)) { return pf(*this); }  The function pf should do its work and return the stream

 #include  Define a function with the required signature (below)  Do your work and return the stream: ostream& nl(ostream& os) { return os << '\n'; } int main() { cout << "newlines" << nl << "between" << nl << "each" << nl << "word" << nl; } cout << nl becomes… cout.operator<<(nl), which executes nl(cout), which executes cout << ‘\n’

 setw(n), setfill(c), setprecision(n), etc.  Must include for these  Example: C04/Manips.cpp  Difficult to implement your own  not portable  Use Effectors instead  (see next slide)

 Create a class whose constructor formats a string according to its purpose  That class also provides an operator<<  Example: C04/Effector.cpp

 The streams we’ve been using traffic in bytes (char)  You can have streams that use wide characters (wchar_t)  displaying foreign characters requires platform support outside of C++  C++ just stores code points internally

 The template that governs the standard stream classes: template > class basic_istream {...};  typedef basic_istream istream; typedef basic_istream wistream; typedef basic_ifstream ifstream; typedef basic_ifstream wifstream; typedef basic_istringstream istringstream; typedef basic_istringstream wistringstream;

 Cultural customization of I/O formatting  A stream has an associated locale  Can change it with imbue( )  Example: Locale.cpp (Windows only)  Java’s locale support is much better