Compaq_C++____________________________________ Class Library Reference Manual Order Number: AA-PY3EB-TK June 1999 This document describes a library of C++ classes. Revision/Update Information: This is a revised manual. Software Version: C++ Version 5.3 or later C++ Class Library Version 4.0 Compaq Computer Corporation Houston, Texas __________________________________________________________ First Printing, September 1992 First Revision, June 1993 Second Revision, April 1996 Third Revision, June 1999 The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under a license and may be used or copied only in accordance with the terms of such license. No responsibility is assumed for the use or reliability of software on equipment that is not supplied by Digital Equipment Corporation or its affiliated companies. Restricted Rights: Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013. ©1993-1999 Digital Equipment Corporation. All Rights Reserved. Compaq, the Compaq logo, and Alpha, DEC, DEC FUSE, DECthreads, DIGITAL, OpenVMS, ULTRIX, VAX, VMS are Registered in U.S. Patent and Trademark Office. The following are third-party trademarks: AT&T is a registered trademark of American Telephone & Telegraph Company. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company, Ltd. This document is available on CD-ROM. ZK6026 This document was prepared using DECdocument, Version 3.2-1M. ________________________________________________________________ Contents Preface.................................................. vii 1 Overview 1.1 Thread Safe Programming......................... 1-1 2 complex Package Global Declarations............................. 2-2 complex class................................... 2-4 c_exception class............................... 2-11 3 generic Package Global Declarations............................. 3-3 4 iostream Package Global Declarations............................. 4-5 filebuf class................................... 4-14 fstream class................................... 4-19 IAPP(TYPE) class................................ 4-22 ifstream class.................................. 4-24 IMANIP(TYPE) class.............................. 4-27 IOAPP(TYPE) class............................... 4-29 IOMANIP(TYPE) class............................. 4-31 ios class....................................... 4-33 iostream class.................................. 4-46 iostream_withassign class....................... 4-48 istream class................................... 4-50 iii istream_withassign class........................ 4-58 istrstream class................................ 4-60 OAPP(TYPE) class................................ 4-62 ofstream class.................................. 4-64 OMANIP(TYPE) class.............................. 4-67 ostream class................................... 4-69 ostream_withassign class........................ 4-74 ostrstream class................................ 4-76 SAPP(TYPE) class................................ 4-78 SMANIP(TYPE) class.............................. 4-79 stdiobuf class.................................. 4-81 stdiostream class............................... 4-84 streambuf class................................. 4-87 strstream class................................. 4-99 strstreambuf class.............................. 4-101 5 Messages Package Messages class.................................. 5-2 6 Mutex Package Mutex class..................................... 6-2 7 Objection Package Global Declaration.............................. 7-2 Objection class................................. 7-3 8 Stopwatch Package Stopwatch class................................. 8-2 iv 9 String Package String class.................................... 9-2 10 task Package Global Declarations............................. 10-3 erand class..................................... 10-7 histogram class................................. 10-9 Interrupt_handler class......................... 10-12 object class.................................... 10-16 qhead class..................................... 10-20 qtail class..................................... 10-26 randint class................................... 10-31 sched class..................................... 10-33 task class...................................... 10-39 timer class..................................... 10-45 urand class..................................... 10-49 11 vector Package stack(TYPE) class............................... 11-3 vector(TYPE) class.............................. 11-7 Index Figures 4-1 Inheritance Diagram for the iostream Package....................................... 4-2 10-1 Inheritance Diagram for the task Package ..... 10-1 v Tables 1 Conventions Used in this Manual .............. ix vi ________________________________________________________________ Preface This manual describes the library of classes supplied with C++ Version 5.6 for OpenVMS systems. It contains detailed information on members of these classes (including member functions) and information on other associated functions, variables, and macros. Intended Audience This manual is intended for experienced programmers who have a basic understanding of the C++ language, and who are using C++ with the OpenVMS operating system in either a single or multiple platform environment. Some familiarity with the operating system is assumed. Document Structure This manual consists of an introductory chapter and 10 chapters describing each of the packages of predefined classes supplied with the C++ compiler. Associated Documents The following documents contain information related to this manual: o Using Compaq C++ for OpenVMS VAX This manual supplies information needed to use C++ on OpenVMS systems. o Stroustrup, Bjarne. Stroustrup, The C++ Programming Language, 3nd Edition, Addison-Wesley, 1997. Reading, Massachusetts. Addison-Wesley, 1997. vii This text combines a user guide and language reference manual. o Stroustrup, Bjarne and Margaret Ellis. The Annotated C++ Reference Manual. Reading, Massachusetts. Addison- Wesley, 1990. This text contains the current language definition of C++. viii o C Run-Time Library Reference Manual for OpenVMS Systems This manual describes C run-time library routines that are supported for C++. o Compaq C++ Installation Guide for OpenVMS VAX This guide supplies information needed to ensure that the C++ Class Library installs correctly on OpenVMS systems and is accessible to the C++ compiler. Conventions Table 1 lists the conventions used in this manual. Table_1_Conventions_Used_in_this_Manual___________________ Conventions_____________Meaning___________________________ class complex { A vertical ellipsis indicates that . some intervening program code or . output is not shown. Only the more . pertinent material is shown in the }; example. , . . . A horizontal ellipsis in a syntax description indicates that you can enter additional parameters, options, or values. A comma preceding the ellipsis indicates that successive items must be separated by commas. The complex class . . . Monospaced type denotes the names of C++ language elements, and also The get() func- the names of classes, members, tion . . . and nonmembers. Monospaced type is also used in text to reference code elements displayed in examples. (continued on next page) ix Table_1_(Cont.)_Conventions_Used_in_this_Manual___________ Conventions_____________Meaning___________________________ italic Italic type denotes the names of variables that appear as parameters or in arguments to functions. boldface Boldface type in text indicates the first instance of terms ________________________defined_in_text.__________________ Reader's Comments You may send your comments or suggestions regarding this manual, or any C++ document, by electronic mail to the following Internet address: cxx_docszko.dec.com x 1 ________________________________________________________________ Overview The C++ Class Library is a set of headers and other files implementing a collection of basic C++ classes. In the library, these classes are arranged in functionally related groups called packages. The DEC C++ Class Library makes use of other run-time libraries. ________________________Note ________________________ Identifiers beginning with cxxl or CXXL are reserved for the DEC C++ Class Library and should not be used by customer programs except as specified in this manual. Error message examples in this manual are displayed without their OpenVMS facility, error severity, or message identification code prefixes. You can achieve this result by entering the following DCL command: $ set message/nofac/nosev/noid _____________________________________________________ 1.1 Thread Safe Programming Developers of multithreaded applications should note the following: o Internal class library data is thread safe; multiple threads can access the DEC C++ Class Library simul- taneously without compromising the integrity of the internal data. Overview 1-1 Overview 1.1 Thread Safe Programming o The predefined stream objects, cerr, cin, clog, and cout are thread safe. However, you need to provide synchronization around sequences of operations on these objects. For more information on synchronizing access to the predefined stream objects, see Chapter 4. o User-defined objects are not thread safe; users must provide synchronization for such objects if they are shared between threads. For more information on synchronizing access to user-defined objects, see Chapter 6. o The ios class member function sync_with_stdio() is not thread safe; if your application calls this function, the call must come before any threads use the predefined stream objects: cerr, cin, clog, or cout. o Generation of error messages within the vector package is not thread safe; the package uses static data members to handle the current error message and there is no synchronization between threads. Digital recommends that you define a single Mutex object to synchronize all use of the vector package. o The task package is not thread safe; only one task can execute at a time. 1-2 Overview 2 ________________________________________________________________ complex Package The complex package provides ways to perform arithmetical operations, such as initialization, assignment, input, and output, on complex values (that is, numbers with a real part and an imaginary part). Additionally, this package supports operations that are unique to complex values, such as principal argument operations, conjugate operations, and conversions to and from polar coordinates. With the c_exception class and its c_exception function, the complex package also provides a mechanism for reporting and handling complex arithmetical errors. complex Package 2-1 Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the complex package but they are not members of the complex class. Header #include Alternative Header #include Declarations typedef int (*cxxl_p_complex_error_t)(c_exception &error_information); static const complex_zero (0, 0); cxxl_p_complex_error_t set_complex_error(cxxl_p_complex_error_t p_complex_error); Type cxxl_p_complex_error_t Is the type of the complex_error function. Data static const complex_zero (0, 0) Is a constant object of type complex and value 0 created in each module that uses the complex package. Function cxxl_p_complex_error_t set_complex_error (cxxl_p_complex_ error_t p_complex_error) Causes the function pointed to by p_complex_error to be called instead of the complex_error function on subsequent complex arithmetical errors. If set_complex_error() previously has not been called, then it returns 0; otherwise, it returns the address of the last function passed to it. 2-2 complex Package Global Declarations See the Other Function section of c_exception class for a description of the error-handling function. complex Package 2-3 complex class ________________________________________________________________ complex class Provides a representation of, and lets you perform operations on, complex values. Header #include Alternative Header #include Declaration class complex { friend complex polar(double, double = 0); friend double abs(const complex &); friend double norm(const complex &); friend double arg(const complex &); friend double arg1(const complex &); friend complex conj(const complex &); friend complex sin(const complex &); friend complex sinh(const complex &); // c_exception OVERFLOW friend complex cos(const complex &); friend complex cosh(const complex &); // c_exception OVERFLOW friend complex tan(const complex &); friend complex tanh(const complex &); friend double imag(const complex &); friend double real(const complex &); friend complex log(const complex &); // c_exception SING // c_exception OVERFLOW UNDERFLOW friend complex exp(const complex &); friend complex pow(double, const complex &); friend complex pow(const complex &, int); friend complex pow(const complex &, double); friend complex pow(const complex &, const complex &); friend complex sqrt(const complex &); friend complex sqr(const complex &); friend complex operator-(const complex &); friend complex operator+(const complex &, const complex &); 2-4 complex Package complex class friend complex operator-(const complex &, const complex &); friend complex operator*(const complex &, const complex &); friend complex operator/(const complex &, const complex &); friend int operator==(const complex &, const complex &); friend int operator!=(const complex &, const complex &); friend ostream &operator<<(ostream &, const complex &); friend istream &operator>>(istream &, complex &); public: complex(double, double = 0); complex(); inline complex &operator-=(const complex &); inline complex &operator+=(const complex &); complex &operator*=(const complex &); complex &operator/=(const complex &); }; Description This class contains methods to perform complex value operations. These include arithmetical, assignment, and comparison operators for complex values; Cartesian and polar coordinates; mixed-mode arithmetic; and mathematical functions for complex values equivalent to standard mathematical functions. Exception Handling When a complex arithmetical error is detected, a c_ exception object is created with one of the following values for type: __________________________________________________________ Value________Error_Description____________________________ OVERFLOW Value too large to be represented SING Function undefined for argument UNDERFLOW____Value_too_small_to_be_represented____________ This object is then passed to the complex_error function (see the c_exception class). complex Package 2-5 complex class Constructors and Destructors complex() Constructs and initializes a complex value to 0. complex(double x, double y = 0) Constructs and initializes a complex value from Cartesian coordinates. Overloaded Operators complex operator + (const complex &z1, const complex &z2) Returns the arithmetical sum of the complex values z1 and z2. complex operator - (const complex &z1) Returns the arithmetical negation of a complex value. complex operator - (const complex &z1, const complex &z2) Returns the arithmetical difference of complex values. That is, z2 is subtracted from z1. complex operator * (const complex &z1, const complex &z2) Returns the arithmetical product of the complex values z1 and z2. complex operator / (const complex &z1, const complex &z2) Returns the arithmetical quotient of complex values. That is, z1 is divided by z2. inline complex &operator += (const complex &z1) Assigns the arithmetical sum of complex values to the complex object on the left side of an equation. That is, z1+=z2 is equivalent to z1=z1+z2. inline complex &operator -= (const complex &z1) Assigns the arithmetical difference of two complex numbers to the complex object on the left side of an equation. That is, z1-=z2 is equivalent to z1=z1-z2. 2-6 complex Package complex class complex &operator *= (const complex &z2) Assigns the arithmetical product of two complex numbers to the complex object on the left side of an equation. That is, z1*=z2 is equivalent to z1=z1*z2. complex &operator /= (const complex &z2) Assigns the arithmetical quotient of two complex numbers to the complex object on the left side of an equation. That is, z1/=z2 is equivalent to z1=z1/z2. ostream &operator << (ostream &s, const complex &z1) Sends a complex value to an output stream in the format (real,imag). It returns the left argument s. istream &operator >> (istream &s, complex &z1) Takes a complex value from an input stream. The numbers may be of the forms (real,imag) or (real), where real and imag are what the iostream library accepts for parameters of type double. The iostream library also determines how to handle white space. This operator returns the left argument s. The following input format omissions will cause an error: o Parenthesis missing before a complex value o Comma missing before the imaginary part of a complex value, if any o Parenthesis missing after the complex value int operator == (const complex &z1, const complex &z2) Compares two complex values and returns a nonzero value if the two numbers are equal; otherwise, it returns 0. int operator != (const complex &z1, const complex &z2) Compares two complex values and returns a nonzero value if the two numbers are not equal; otherwise, it returns 0. complex Package 2-7 complex class Other Functions double abs(const complex &z1) Returns the absolute value (magnitude) of a complex value. double arg(const complex &z1) Returns the angle, in radians, of a complex value. The result is normalized such that it is greater than or equal to 0, and less than 2*. double arg1(const complex &z1) Returns the principal value of the angle, in radians, of a complex value. The result is normalized such that it is greater than -, and less than or equal to . complex conj(const complex &z1) Returns the conjugate of a complex value; that is, if the number is (real, imag), then the result is (real, -imag). complex cos(const complex &z1) Returns the cosine of a complex value. complex cosh(const complex &z1) Returns the hyperbolic cosine of a complex value. The value of real(z1) must be small enough so that exp(real(z1)) does not overflow; otherwise, the function creates a c_exception object and invokes the complex_error function. complex exp(const complex &z1) Returns the value of e (2.71828...) raised to the power of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_error function. double imag(const complex &z1) Returns the imaginary part of a complex value. complex log(const complex &z1) Returns the natural logarithm (base e, 2.71828...) of a complex value. The conditions described for cosh() must 2-8 complex Package complex class be met; otherwise, it creates a c_exception object and invokes the complex_error function. double norm(const complex &z1) Returns the square of the absolute value (magnitude) of a complex value. complex polar(double rho, double theta = 0) Creates a complex value given a pair of polar coordinates (magnitude rho and angle theta, in radians). complex pow(const complex &z1, int i2) Returns the value of z1 raised to the power of i2. complex pow(const complex &z1, double x2) Returns the value of z1 raised to the power of x2. complex pow(double z1, const complex &z2) Returns the value of z1 raised to the power of z2. complex pow(const complex &z1, const complex &z2) Returns the value of z1 raised to the power of z2. double real(const complex &z1) Returns the real part of a complex value. complex sin(const complex &z1) Returns the sine of a complex value. complex sinh(const complex &z1) Returns the hyperbolic sine of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_ error function. complex sqr(const complex &z1) Returns the square of a complex value. complex sqrt(const complex &z1) Returns the square root of a complex value. complex tan(const complex &z1) Returns the tangent of a complex value. complex Package 2-9 complex class complex tanh(const complex &z1) Returns the hyperbolic tangent of a complex value. The conditions described for cosh() must be met; otherwise, it creates a c_exception object and invokes the complex_ error function. Examples 1. complex zz(3,-5); Declares zz to be a complex object and initializes it to the value of real part 3 and imaginary part -5. 2. complex myarray[30]; Declares an array of 30 complex objects, all initial- ized to (0,0). 3. complex zz; while (!(cin >> zz).eof()) cout << zz << endl; Reads a stream of complex values [for example, (3.400000,5.000000)] and writes them in the default format [for example, (3.4, 5)]. 4. complex cc = complex (3.4,5); cout << real(cc) << "+" << imag(cc) << "*i"; Prints out 3.4 as the real part of a complex object and 5 as the imaginary part. The result is 3.4+5*i. 2-10 complex Package c_exception class ________________________________________________________________ c_exception class Contains information on a complex arithmetical exception. Header #include Alternative Header #include Declaration class c_exception { friend complex exp(const complex &); friend complex sinh(const complex &); friend complex cosh(const complex &); friend complex log(const complex &); friend int complex_error(c_exception &); public: int type; char *name; complex arg1; complex arg2; complex retval; public: c_exception(char *, const complex &, const complex & = complex_zero); }; Description Objects of this class handle exceptions for complex arithmetic. This includes information on functions, parameters, error types, and default return values. complex Package 2-11 c_exception class Data Members complex arg1 Is the left argument of the function that incurred the error. complex arg2 Is the right argument of the function that incurred the error. char *name Is the name of the function that incurred the error. complex retval Is the value to be returned by the function that incurred the error. You may use the complex_error(c_exception &) function to change this value. int type Is one of these kinds of error: SING, OVERFLOW, or UNDERFLOW. Constructor c_exception(char *function_name, const complex &function_ arg1, const complex &function_arg2 = complex_zero) Constructs a complex arithmetical exception object, with reference to the name and arguments of the function that incurred the error. Other Function int complex_error (c_exception &error_information) Is the default error-handling function that is called by certain complex arithmetical functions in this package (namely, cosh, exp, log, and sinh) when those functions detect an arithmetical error. You may replace this function with your own function that takes an identical parameter list and returns a value as specified in the following table: 2-12 complex Package c_exception class __________________________________________________________ Return Value from Error-handling Action Taken by Complex Arithmetical Function______________Function____________________________ 0 Set the global value errno; if the error type is SING, print an error message. non 0 Do not set errno; do not print an ______________________error_message.______________________ To substitute your own error-handling function, pass a pointer to your function to the set_complex_error function. (See the Function section under Global Declarations for the complex package.) The complex arithmetical functions that invoke the error handling function always return the value specified in error_information.retval. Your error-handling function may set this value. complex Package 2-13 3 ________________________________________________________________ generic Package The generic package provides ways to simulate parame- terized types by allowing the instantiation of class declarations using the macro facilities of the C++ preprocessor. You can use the generic package to construct container classes. The actual types of the data members are passed at compile time as parameters to the class when you use the class name. To declare a generic type: 1. Define a name for the class and specify the number of type parameters: #define YOUR_CLASS_NAME(TYPE_PARAMETER_NAME) name2(TYPE_PARAMETER_NAME, YOUR_CLASS_NAME) To specify two type parameters, use the name3 macro. 2. Define the class body as a macro: #define YOUR_CLASS_NAMEdeclare(TYPE_PARAMETER_NAME) class { . . . }; #define YOUR_CLASS_NAMEimplement(TYPE_PARAMETER_NAME) . . . 3. Declare the actual class: declare(YOUR_CLASS_NAME, ACTUAL_TYPE_NAME) By substituting one or another class of ACTUAL_TYPE_ NAME, you can declare multiple instances of the generic class template with various component types. For example, depending on the type parameter you use, you can declare such types as list of ints, list of Strings, or list of lists of Strings. If it is not a type name, ACTUAL_TYPE_NAME must be a typedef name. generic Package 3-1 You must do this in each compilation unit that uses the parameterized type with a given parameter. 4. Define the functions or static data of the actual class. implement(YOUR_CLASS_NAME, ACTUAL_TYPE_NAME) You must do this once in each program that uses the parameterized type with a given parameter. 5. Declare an instance of the class you have declared by specifying objects of type YOUR_CLASS_NAME(ACTUAL_TYPE_ NAME), as follows: YOUR_CLASS_NAME(ACTUAL_TYPE_NAME) object1, object2; 3-2 generic Package Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the generic package but they are not members of any class. Header #include Alternative Header #include Compile-Time Parameters TYPE, TYPE1, TYPE2-The types for which this class is parameterized; TYPE, TYPE1, or TYPE2 must be an identifier. CLASS-The class that is parameterized. For a vector of integers, for example, CLASS is vector and TYPE is int. Declarations typedef int (*GPT)(int, char *); int genericerror(int n, char *msg); Type GPT Is a pointer to a generic error-handling function. Function int genericerror (int n, char *msg) Is the default error-handling function; it prints an error number (n) and message (msg) on cerr and calls abort(). Macros Macros provide preprocessor facilities for simulating parameterized types. The following macros are defined for the generic package: generic Package 3-3 Global Declarations callerror(CLASS, TYPE, N, S) Calls the current error handler for a given instance of a parameterized class. CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers); the type must be an identifier (for example, char* is not valid). N denotes the first argument to pass to the error handler; the default is the function genericerror(int, char*). S denotes the second argument to pass to the error handler. declare(CLASS, TYPE) Declares the class specified by a macro with the name of the generic class. The word declare follows the class name (for example, vectordeclare). It also defines the inline member functions of the class. CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers). The type must be an identifier (for example, char* is not valid). declare2(CLASS, TYPE1,TYPE2) Declares the class specified by a macro with the name of the generic class. The name is followed by the word declare2. The declare2 macro differs from the declare macro only in that you use it to declare two type parameters, TYPE1 and TYPE2. errorhandler(CLASS, TYPE) Is the name of the pointer to the error handler for a given instance of a parameterized class (for example, intvectorhandler to handle errors for a vector of integers). CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers). The type must be an identifier (for example, char* is not valid). implement(CLASS, TYPE) Defines the noninline member functions of a class, specified by a macro with the name of the generic class. The name is followed by the word implement (for example, 3-4 generic Package Global Declarations vectorimplement). The implement macro takes the same arguments as the declare macro. implement2(CLASS, TYPE1,TYPE2) Defines the noninline member functions of a class, specified by a macro with the name of the generic class. The name is followed by the word implement2. The implement2 macro differs from the implement macro only in that you use it to declare two type parameters, TYPE1 and TYPE2. name2(S1,S2) Concatenates two identifier segments to form a new identifier using the ## operator. name3(S1,S2,S3) Concatenates three identifier segments to form a new identifier using the ## operator. name4(S1,S2,S3,S4) Concatenates four identifier segments to form a new identifier using the ## operator. set_handler(CLASS, TYPE, HANDLER) Specifies a function as the current error handler for a given instance of a parameterized class. Initially, the error-handling function is set to genericerror(int, char*). CLASS denotes the name of the generic class (for example, vector). TYPE denotes the type parameter for which to instantiate the generic class (for example, int to get a vector of integers); the type must be an identifier (for example, char* is not valid). HANDLER denotes a pointer to the function you want to set to the new error handler. Also, you can use the set_handler macro in a function declaration or definition. generic Package 3-5 Global Declarations Example The following program shows the use of the genericerror function and associated macros: extern "C" { #include #include #include } #include #define my_vector(T) name2(T, my_vector) // Declare a vector of objects of type T (the class and extern data) #define my_vectordeclare(T) \ class my_vector(T) \ { \ private: \ int s; \ T *p; \ public: \ my_vector(T)(int); \ ~my_vector(T)(); \ T &operator[](int); \ }; \ extern GPT errorhandler(my_vector, T); \ extern GPT set_handler(my_vector, T, GPT); 3-6 generic Package Global Declarations // Implement a vector of objects of type T // (Define the functions and global data) #define my_vectorimplement(T) \ my_vector(T)::my_vector(T)(int size) \ { \ s = size; \ p = new T[size]; \ } \ my_vector(T)::~my_vector(T)() \ { \ delete[] p; \ } \ T &my_vector(T)::operator[](int i) \ { \ if(i < 0 || i >= s) \ { \ callerror(my_vector, T, i, "Index out of bounds"); \ static T error_object; \ return error_object; \ } \ return p[i]; \ } \ GPT errorhandler(my_vector, T) = &genericerror; \ GPT set_handler(my_vector, T, GPT new_genericerror) \ { \ GPT old_genericerror = errorhandler(my_vector, T); \ errorhandler(my_vector, T) = new_genericerror; \ return old_genericerror; \ } // Declare and implement vector of int declare(my_vector, int) implement(my_vector, int) // Error-handling function my_handler( int n, char *msg ) generic Package 3-7 Global Declarations { fflush(stderr); printf("in my_handler(%d,\"%s\")\n", n, msg); fflush(stdout); return 0; } int main(int argc, char *argv[]) { my_vector(int) v1(10); GPT old_error_handler; // Set the handler to a function that does not abort old_error_handler = set_handler(my_vector, int, &my_handler); v1[12345] = 0; // Restore the handler and cause an error // This should abort old_error_handler = set_handler(my_vector, int, old_error_handler); v1[12345] = 0; return EXIT_SUCCESS; } See Also vector Package 3-8 generic Package 4 ________________________________________________________________ iostream Package Classes in the iostream package provide methods to handle input and output streams, including reading and writing built-in data types. You also can extend certain methods described here to handle class types. This package includes, among others, the classes ios and streambuf, and the subclasses derived from these base classes. Figure 4-1 shows the inheritance structure of the iostream package. In the diagram, arrows point from the base classes to derived classes. The istream (input stream) class supports input operations (extractions); the ostream (output stream) class supports output operations (insertions). The iostream class derives from both istream and ostream, and supports both extractions and insertions. The following stream objects are predefined: cin An istream_withassign object linked to standard input cout An ostream_withassign object linked to standard output cerr An ostream_withassign object linked to standard error that supports unbuffered output clog An ostream_withassign object linked to standard error that supports buffered output To generate output, you apply the insertion operator (<<) to cout, as shown in the following example: cout << "Hello\n" ; iostream Package 4-1 Figure 4-1 Inheritance Diagram for the iostream Package Obtaining input is similar to generating output, except that you apply the extraction operator (>>) to cin, as shown in the following example: int eye, jay ; cin >> eye >> jay ; If you include these fragments of code in a program, your system expects users to type in two integer values (for eye and jay) from a terminal. The iostream package supplies predefined extraction and insertion operators for all built-in data types, including char*. This package also supports file manipulation. To connect a specific file to your program, instantiate one of the following class types: 4-2 iostream Package ifstream (for file input) ofstream (for file output) fstream (for both input and output) To format within character arrays, the iostream package includes the following associated class types: istrstream (for fetching characters from an array) ostrstream (for storing characters into an array) strstream (for both fetching and storing characters into an array) ________________________Note ________________________ On systems with IEEE floating-point arithmetic, certain values may be printed as symbols for Infinity (for example, INF) or Not a Number (for example, NaN). _____________________________________________________ Deriving Your Own Class from ios If you derive your own class from the ios class, or from one of its derived classes, the ios subobject must be initialized properly during instantiation. Specifically, you must ensure that the streambuf pointer within the ios subobject is valid. To do this, you can specify the ios(streambuf *) construc- tor as a member initializer for your class constructor. Optionally, you can call the ios::init(streambuf *) member function. Thread Safety The predefined stream objects, cerr, cin, clog, and cout are thread safe only for individual calls into the DEC C++ Class Library. You must provide synchronization around sequences of calls. For more information on synchronizing access to predefined stream objects, see the section on Global Declarations in this chapter. User-defined stream objects are not thread safe, so you must provide synchronization around individual calls as well as sequences of calls. For more information on synchronizing access to user-defined objects, see iostream Package 4-3 Chapter 6 and the section on Global Declarations in this chapter. The ios member function sync_with_stdio() is not thread safe. If your application calls this function, it must make the call before any threads use cerr, cin, clog, or cout. 4-4 iostream Package Global Declarations ________________________________________________________________ Global Declarations These declarations are used by the iostream package but they are not members of any class. Header #include Alternative Header #include Declarations typedef long streamoff typedef long streampos ios &dec(ios &s); ios &hex(ios &s); ios &oct(ios &s); ios &lock(ios &s); ios &unlock(ios &s); istream &ws(istream &i); ostream &endl(ostream &o); ostream &ends(ostream &o); ostream &flush(ostream &o); Types typedef long streamoff Is the type representing a character offset into a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class. typedef long streampos Is the type representing a character position in a stream. For more information, see the description of the seekoff and seekpos functions in the streambuf class. iostream Package 4-5 Global Declarations Manipulators The following functions insert values into a stream, extract values from a stream, or specify the conversion base format. For more information on the conversion base format flags, see the ios class. ios &dec(ios &s) Sets the conversion base format for s to decimal, essentially clearing the ios::oct and ios::hex flags and setting the ios::dec flag. ios &hex(ios &s) Sets the conversion base format for s to hexadecimal, essentially clearing the ios::oct and ios::dec flags and setting the ios::hex flag. ios &oct(ios &s) Sets the conversion base format for s to octal, es- sentially clearing the ios::dec and ios::hex flags and setting the ios::oct flag. istream &ws(istream &i) Extracts (skips) white-space characters from i. ostream &endl(ostream &o) Ends a line by inserting a new-line character into o and flushing o. ostream &ends(ostream &o) Ends a string by inserting a null '/0' character into o. ostream &flush(ostream &o) Flushes o. Synchronizing Access to Predefined Stream Objects The following unparameterized manipulators are for use in synchronizing access to the predefined stream objects, cerr, cin, clog, and cout: 4-6 iostream Package Global Declarations ios &lock(ios &s) Locks s if s is one of the predefined stream objects. ios &unlock(ios &s) Unlocks s if s is one of the predefined stream objects. If your application needs to lock two or more of these objects at the same time, your application must adhere to the following locking order: iostream Package 4-7 Global Declarations 1. cin 2. cerr 3. clog 4. cout For example, if your application needs to lock both cerr and cout, lock cerr first and cout second. The unlocking order is not important. Keep in mind that when your application calls a member function for a predefined stream object, the member function will typically lock the object for the duration of the call. Therefore, if your application has locked one of the stream objects and then uses another, this use must also adhere to the predefined locking order. For example, your application should not send output to cerr while cout is locked. The locking order necessarily matches the default ties between the stream objects as follows: cin is tied to cout cerr is tied to cout clog is tied to cout cout has no ties Any input/output operation on a stream object causes the iostream package to flush the object to which it is tied. Thus, an output to cerr flushes cout. Examples 1. #include #include int main () { int value = 10; cout << hex << value << ','; // Change the base conversion format to // hexadecimal; note that the default is // decimal as set by the ios constructors. cout << value << ','; // The base conversion format set in the // previous line is still active. 4-8 iostream Package Global Declarations cout << dec << value << endl; // Change the base conversion format to // decimal; lastly, insert a new-line // character into the stream and flush // cout. return 0; } The output is a,a,10. 2. #include #include void print_name(String &name) { cout << lock << "Hello, " << name << endl << unlock; } This synchronizes access to the cout object so that the "Hello, ", name, and new-line character are written to cout as a single unit. If you do not use the lock and unlock manipulators in this example, another thread could possibly insert its own text into cout in the midst of your output. iostream Package 4-9 Global Declarations Header #include Alternative Header #include Declarations SMANIP(long) resetiosflags(long); SMANIP(long) setiosflags(long); SMANIP(int) setfill(int); SMANIP(int) setprecision(int); SMANIP(int) setw(int w); SMANIPREF(Mutex) lock(Mutex &m) SMANIPREF(Mutex) unlock(Mutex &m) Functions These functions are used for extending the iostream package with user-defined parameterized manipulators. SMANIP(long) resetiosflags(long x) In the stream (ios or a stream derived from ios), clears the format flags denoted by x. SMANIP(int) setfill(int x) Sets the fill character to be the value specified by x. The fill character is a data member of the ios class; however, setting it with this function affects only output streams. SMANIP(long) setiosflags(long x) In the stream (ios or a stream derived from ios), turns on the format flags denoted by x. If you are setting a flag that is part of a collection (for example, basefield), note that this manipulator does not clear the other flags in the collection. 4-10 iostream Package Global Declarations SMANIP(int) setprecision(int x) Sets the variable that controls the number of digits inserted by the floating-point inserter to be x. This variable is a data member of the ios class; however, setting it with this function affects only output streams. SMANIP(int) setw(int w) In the stream (ios or a stream derived from ios), sets the field width of the stream to w. Synchronizing Access to User-Defined Stream Objects The following parameterized manipulators are for use in synchronizing access to user-defined stream objects. To use these manipulators, you must first define a Mutex object, which you then pass to the manipulator. The association of a Mutex object with a stream object is not enforced by the iostream package. This association is enforced only by you, the programmer. Refer to Chapter 6 for information on the Mutex class. SMANIPREF(Mutex) lock(Mutex &m) Locks the recursive Mutex represented by m. SMANIPREF(Mutex) unlock(Mutex &m) Unlocks the recursive Mutex represented by m. Examples 1. char c; cin >> resetiosflags(ios::skipws) >> c >> setiosflags(ios::skipws); Turns off the flag (resets it to 0) that tells the extractor (>>) to skip leading white space and then turns that flag back on again (sets it to 1). iostream Package 4-11 Global Declarations 2. cout.fill(*) cout.setf(ios::left,ios::adjustfield); cout << setw(6) << 23 << "," ; cout.fill(%); cout.setf(ios::right,ios::adjustfield); cout << setw(4) << 34 << "\n" ; Places padding characters (specified by the fill state variable) after the first number and before the second number. The output is 23****,%%34. 3. #include #include #include #include main () { String name("Henry"); void print_name (String &, ostream &, Mutex &); ofstream mystream(1); Mutex mystream_lock; print_name(name, mystream, mystream_lock); return 0; } void print_name(String &name, ostream &stream, Mutex &stream_lock) { stream << lock(stream_lock) << "Hello, " << name << endl << unlock(stream_lock); } This example associates a Mutex object with a stream object to synchronize access to the stream. The Mutex is locked before using the stream and then unlocked afterwards. For the synchronization to work properly, each thread that uses this stream must perform the same lock/unlock sequence with the same Mutex. 4-12 iostream Package Global Declarations See Also IMANIP(TYPE) class IOMANIP(TYPE) class OMANIP(TYPE) class SMANIP(TYPE) class iostream Package 4-13 filebuf class ________________________________________________________________ filebuf class Provides a data buffer abstraction for input/output facilities through file descriptors. Header #include Alternative Header #include Declaration class filebuf: public streambuf { public: static const int openprot; filebuf(); filebuf(int fd); filebuf(int fd, char *p, int len); ~filebuf(); filebuf *attach(int fd); filebuf *close(); int fd(); int is_open(); filebuf *open(const char *name, int mode, int prot = openprot); virtual int overflow(int = EOF); virtual streampos seekoff(streamoff, seek_dir, int mode); virtual streampos seekpos(streampos, int mode); virtual streambuf *setbuf(char *p, int len); virtual int sync(); virtual int underflow(); }; 4-14 iostream Package filebuf class Description This class specializes the streambuf class to use a file as a repository of characters. Writing to the file consumes characters; reading from the file produces characters. Files that allow searches are said to be seekable. When a file is readable and writable, the filebuf object permits character insertion and extraction. If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer with a length specified by BUFSIZ as defined in stdio.h. The package then issues the following warning: Warning; a null pointer to streambuf was passed to ios::init() Data Member const int openprot = 0644 Provides default protection for the open() function. (For an explanation of the file protection, see the C Run-Time Library Reference Manual.) Constructors and Destructors filebuf() Constructs a filebuf object that is initially closed. filebuf(int fd) Constructs a filebuf object connected to file descriptor fd. filebuf(int fd, char *p, int len) Constructs a filebuf object connected to file descriptor fd, which is initialized to use the reserve area (buffer) starting at p and containing len bytes. ~filebuf() Deletes a filebuf object. iostream Package 4-15 filebuf class Member Functions filebuf *attach(int fd) Connects the filebuf object to an open file whose descriptor is passed through the fd argument. It normally returns a reference to the filebuf object, but returns 0 if the filebuf object is connected to an open file. filebuf *close() Flushes any waiting output, closes the file descriptor, and disconnects a filebuf object. Unless an error occurs, the filebuf object's error state will be cleared. The close() function returns the address of the filebuf object unless errors occur, in which case this function returns 0. Even if errors occur, close() leaves the file descriptor and filebuf object closed. int fd() Returns the file descriptor associated with a filebuf object. If the filebuf object is closed, fd returns EOF. int is_open() Returns a nonzero value when a filebuf object is connected to a file descriptor; otherwise, it returns 0. filebuf *open(const char *name, int mode, int prot) Opens a file with the name specified by name and connects a filebuf object to it. If the file does not exist, the function tries to create it with the protection mode prot unless ios::nocreate is specified in mode. By default, prot is filebuf::openprot. The function fails if the filebuf object is open. The open() function normally returns the address of the filebuf object, but returns 0 if an error occurs. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode, see the Enumerated Types section for the ios class. 4-16 iostream Package filebuf class virtual int overflow(int c) Called to consume characters in classes derived from streambuf. If c is not EOF, this function must also either save c or consume it. Although it can be called at other times, this function usually is called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr(), call setp() to establish a new put area, and (if c != EOF) store c using sputc(). A call to overflow(c) should return EOF to indicate an error; otherwise, it should return something else. virtual streampos seekoff(streamoff off, seek_dir dir, int mode) Moves the get pointer, put pointer, or both as designated by the off and dir arguments. It may fail if the file does not support seeking, or if the attempted motion is otherwise invalid (for example, attempting to seek a position before the beginning of the file). The off argument is interpreted as a count relative to the place in the file specified by dir. The mode argument is ignored. A call to seekoff() returns the new position or EOF if a failure occurs. After a failure, the position of the file is undefined. virtual streampos seekpos(streampos pos, int mode) Moves the file to a position pos. The mode argument is ignored. The function normally returns pos but it returns EOF on failure. virtual streambuf *setbuf(char *p, int len) Sets up the reserve area as the number of bytes specified in the second argument, beginning at the pointer specified in the first argument. If the pointer is null, or the number of bytes is less than 1, the filebuf object is unbuffered. This function normally returns a pointer to the filebuf object; however, if the filebuf object is open and a buffer is allocated, then no changes are made to the reserve area and to the buffering status, and setbuf() returns 0. iostream Package 4-17 filebuf class virtual int sync() Tries to get the state of the get pointer, the put pointer, or both, to agree (synchronize) with the state of the file to which the filebuf object is connected. This means that the function may write characters to the file if some of the characters have been buffered for output, or the function may try to reposition (seek) the file if characters have been read and buffered for input. Normally sync() returns 0, but it returns EOF if synchronization is not possible. When certain characters must be written together, the program should use setbuf() (or a constructor) to ensure that the reserve area is at least as large as the number of characters to be written together. Your program can then call sync(), store the characters, and then call sync() once again. virtual int underflow() Called in classes derived from streambuf to supply characters for fetching; that is, to create a condition in which the get area is not empty. If the function is called when characters occupy the get area, it should create a nonempty area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area. See Also ios class streambuf class 4-18 iostream Package fstream class ________________________________________________________________ fstream class Supports formatted and unformatted input from and output to files. Header File #include Alternative Header #include Declaration class fstream: public iostream { public: fstream(); fstream(const char *name, int mode, int prot = filebuf::openprot); fstream(int fd); fstream(int fd, char *p, int len); ~fstream(); void attach(int fd); void close(); void open(const char *name, int mode, int prot = filebuf::openprot) ; filebuf *rdbuf(); void setbuf(char *p, int len); }; Description This class specializes the iostream class to files by using a filebuf object to do the input and output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. iostream Package 4-19 fstream class Constructors and Destructors fstream() Constructs an unopened fstream object. fstream(int fd) Constructs an fstream object connected to the file whose descriptor is passed through the fd argument. The file must be open. fstream(int fd, char *p, int len) Constructs an fstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered. fstream(const char *name, int mode, int prot) Constructs an fstream object and opens the file specified by the name argument. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot. If the open action fails, the error state (io_state) of the constructed fstream object indicates failure. ~fstream() Deletes an fstream object. Member Functions void attach(int fd) Connects an fstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the fstream object is connected to a file, in which case ios::failbit is set in the filebuf object's error state. void close() Closes any associated filebuf object and consequently breaks the connection of the fstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails. 4-20 iostream Package fstream class void open(const char *name, int mode, int prot) Opens a file with the file name specified by name and connects the fstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot. Failure occurs if the fstream object is open or when the call to the filebuf object's open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_ mode, see the Enumerated Types section for the ios class. filebuf *rdbuf() Returns a pointer to the filebuf object associated with the fstream object. This function has the same meaning as ios::rdbuf(), but has a different type. void setbuf(char *p, int len) Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason. iostream Package 4-21 IAPP(TYPE) class ________________________________________________________________ IAPP(TYPE) class For an istream object, declares predefined parameterized applicators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the istream object. It must be an identifier. Declaration class IAPP(TYPE) { public: IAPP(TYPE)(istream &(*f)(istream &, TYPE)); IMANIP(TYPE) operator()(TYPE a); }; Constructor IAPP(TYPE) (istream &(*f) (istream &, TYPE)) Creates an applicator; *f is the left operand of the insertion operator. Operator IMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an istream object. 4-22 iostream Package IAPP(TYPE) class See Also IMANIP(TYPE) class iostream Package 4-23 ifstream class ________________________________________________________________ ifstream class Supports formatted and unformatted input from files. Header File #include Alternative Header #include Declaration class ifstream: public istream { public: ifstream(); ifstream(const char *name, int mode = ios::in, int prot = filebuf::openprot); ifstream(int fd); ifstream(int fd, char *p, int len); ~ifstream(); void attach(int fd); void close(); void open(const char *name, int mode = ios::in, int prot = filebuf::openprot); filebuf *rdbuf(); void setbuf(char *p, int len); }; Description This class specializes the istream class to files by using a filebuf object to do the input. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. 4-24 iostream Package ifstream class Constructors and Destructors ifstream() Constructs an unopened ifstream object. ifstream(int fd) Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument. The file must already be open. ifstream(int fd, char *p, int len) Constructs an ifstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered. ifstream(const char *name, int mode, int prot) Constructs an ifstream object and opens the file with the file name specified by name. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot. If the open fails, the error state (io_state) of the constructed ifstream object indicates failure. ~ifstream() Deletes an ifstream object. Member Functions void attach(int fd) Connects an ifstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the ifstream object is connected to a file, in which case ios::failbit is set in the ifstream object error state. void close() Closes any associated filebuf object and consequently breaks the connection of the ifstream object to the file. The error state of the fstream object is cleared except on failure. A failure occurs when the call to the filebuf object's close() function fails. iostream Package 4-25 ifstream class void open(const char *name, int mode, int prot) Opens a file specified by the name argument and connects the ifstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot. Failure occurs if the ifstream object is open or when the call to the filebuf object open() function fails, in which case ios::failbit is set in the filebuf object error state. The members of open_mode are bits that may be joined together by or (because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_ mode, see the Enumerated Types section for the ios class. filebuf *rdbuf() Returns a pointer to the filebuf object associated with the ifstream object. This function has the same meaning as ios::rdbuf() but has a different type. void setbuf(char *p, int len) Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason. 4-26 iostream Package IMANIP(TYPE) class ________________________________________________________________ IMANIP(TYPE) class For an istream object, declares the predefined parame- terized manipulators and provides macros for user-defined parameterized manipulators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the istream object. It must be an identifier. Declaration class IMANIP(TYPE) { public: IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a); friend istream &operator>>(istream &s, IMANIP(TYPE) &m); }; Description These manipulators serve the istream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the iostream class. In its simplest form, a manipulator takes an istream& argument, operates on it in some way, and returns it. iostream Package 4-27 IMANIP(TYPE) class Constructor IMANIP(TYPE)(istream &(*f)(istream &, TYPE), TYPE a) Creates a manipulator; *f is the left operand of the extractor operator. Operator istream &operator >> (istream &s, IMANIP(TYPE) &m) Takes data from an istream object. 4-28 iostream Package IOAPP(TYPE) class ________________________________________________________________ IOAPP(TYPE) class For an iostream object, declares predefined parameterized applicators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the iostream object. It must be an identifier. Declaration class IOAPP(TYPE) { public: IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE)); IOMANIP(TYPE) operator()(TYPE a); }; Constructor IOAPP(TYPE)(iostream &(*f)(iostream &, TYPE)) Creates an applicator. Operator IOMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an iostream object. iostream Package 4-29 IOAPP(TYPE) class See Also IOMANIP(TYPE) class 4-30 iostream Package IOMANIP(TYPE) class ________________________________________________________________ IOMANIP(TYPE) class For an iostream object, declares predefined parameterized manipulators and provides macros for user-defined parameterized manipulators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the iostream object. It must be an identifier. Declaration class IOMANIP(TYPE) { public: IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a); friend istream &operator>>(iostream &s, IOMANIP(TYPE) &m); friend ostream &operator<<(iostream &s, IOMANIP(TYPE) &m); }; IOMANIPdeclare(int); IOMANIPdeclare(long); Description These manipulators serve the iostream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You can also use manipulators to shorten the long names and sequences of operations required by the iostream class. In its simplest form, a manipulator takes an iostream& argument, operates on it in some way, and returns it. iostream Package 4-31 IOMANIP(TYPE) class Two ios manipulators for using Mutex objects, lock and unlock, come in both parameterized and unparameterized forms. The parameterized manipulators let users synchro- nize iostream objects, the parameter being a user-defined Mutex object. To use parameterized manipulators, you must include iomanip.hxx. Unparameterized manipulators let users synchronize the predefined stream objects: cerr, cin, clog, and cout. For examples of using the lock and unlock manipulators, see Chapter 6 and the section on Global Declarations in this chapter. Constructor IOMANIP(TYPE)(iostream &(*f)(iostream &, TYPE), TYPE a) Creates a manipulator. Macro IOMANIPdeclare(TYPE) Declares the manipulators (and the manipulator classes) that have an operator() member function for type TYPE. Operators ostream &operator << (iostream &s, IOMANIP(TYPE) &m) Sends data to an iostream object. istream &operator >> (iostream &s, IOMANIP(TYPE) &m) Takes data from an iostream object. 4-32 iostream Package ios class ________________________________________________________________ ios class Contains state variables common to most of the other classes in the iostream package. Header #include Alternative Header #include Declaration class ios { public: enum io_state { goodbit = 0, eofbit = 01, failbit = 02, badbit = 04 }; enum open_mode { in = 01, out = 02, ate = 04, app = 010, trunc = 020, nocreate = 040, noreplace = 0100 }; enum seek_dir { beg = 0, cur = 01, end = 02 }; enum { skipws = 01, left = 02, right = 04, internal = 010, dec = 020, oct = 040, hex = 0100, showbase = 0200, showpoint = 0400, uppercase = 01000, showpos = 02000, scientific = 04000, fixed = 010000, unitbuf = 020000, stdio = 040000 }; static const long basefield; static const long adjustfield; static const long floatfield; ios(streambuf *); virtual ~ios(); iostream Package 4-33 ios class inline int bad() const; static long bitalloc(); inline void clear(int state = 0); inline int eof() const; inline int fail() const; inline char fill() const; char fill(char); inline long flags() const; long flags(long); inline int good() const; long &iword(int); inline int operator!(); inline operator void *(); inline int precision() const; int precision(int); void *&pword(int); inline streambuf *rdbuf(); inline int rdstate() const; long setf(long setbits, long field); long setf(long); static void sync_with_stdio(); inline ostream *tie() const; ostream *tie(ostream *); long unsetf(long); inline int width() const; int width(int n); static int xalloc(); protected: ios(); void init(streambuf *); inline void setstate(int state); }; Description Classes derived from the ios class provide an interface for transferring formatted and unformatted information into and out of streambuf objects. 4-34 iostream Package ios class Enumerated Types io_state Represents a collection of bits (flags) that describe the internal error states of an object. The values are as follows: goodbit No errors occurred. eofbit End-of-file encountered during an extraction operation. failbit Extraction or conversion failed but the stream is still usable. badbit A severe error, usually in an operation on the associated streambuf object, from which recovery is unlikely. open_mode Represents a collection of bits (flags) for specifying the mode of the open() function. Use this data type with objects of the fstream, ifstream, and ofstream classes. The values are as follows: app Performs a seek to the end-of-file. This appends to the end of the file any subsequent data written to the file. ios::app implies ios::out. ate Performs a seek to the end-of-file during an open() operation. ios::ate does not imply ios::out. in Opens the file for input. Constructions and open operations of ifstream objects imply ios::in. For fstream objects, ios::in signifies that input operations should be allowed if possible. Including ios::in in the modes of an ofstream object is legal, implying that the original file (if it exists) should not be truncated. iostream Package 4-35 ios class out Opens the file for output. Constructions and open operations of ofstream objects imply ios::out. For fstream objects, ios::out indicates that output operations are allowed. trunc Truncates (discards) the contents of the file (if it exists). ios::trunc is implied if ios::out is specified (including implicit specification for ofstream objects), and neither ios::app nor ios::ate is specified. nocreate Causes an open() operation to fail if the file does not exist. noreplace Causes an open() operation to fail if the file exists. 4-36 iostream Package ios class seek_dir Represents a collection of bits for positioning get and put pointers. Use this data type with functions of the filebuf, istream, ostream, and streambuf classes. The values are as follows: beg Indicates the beginning of the stream cur Indicates the current position end Indicates the end of the stream (end-of-file) Data Members const long adjustfield Collectively specifies the flags (bits) that control padding (left, right, and internal). const long basefield Collectively specifies the flags that control base conversion (dec, hex, and oct). const long floatfield Collectively specifies the flags that control floating- point value conversion (fixed and scientific). ________________________Note ________________________ When you set a flag that is part of adjustfield, basefield, or floatfield, you must ensure that the other flags within the collection are cleared. Only one flag within the collection should be set at any one time. Be aware that the setiosflags(flag) manipulator and the setf(flag) member function set only the flag or flags that you specify. If the flag you specify is part of a collection, these do not clear the other flags in the collection. The setf(flag, field) member function is useful for setting fields within a collection. Also, the hex, oct, and dec manipulators do ensure that the other flags within the basefield collection are cleared. _____________________________________________________ iostream Package 4-37 ios class Constructors and Destructors ios() Constructs an ios object with the effect undefined. It lets derived classes inherit the ios class as a virtual base class. The object is initialized with the following default values: __________________________________________________________ Element____Default_Value__________________________________ fill() The space character flags() ios::dec | ios::skipws precision()6 rdstate() ios::goodbit width()____0______________________________________________ ios(streambuf *b) Constructs an ios object, associating the constructed ios object with the streambuf object pointed to by b. The object is initialized with the same default values as the ios() constructor. virtual ~ios() Deletes an ios object. Overloaded Operators When defined, the following operators allow convenient checking of the error state of an ios. int operator !() Returns nonzero if failbit or badbit is set in the error state, which allows the use of such expressions as if (!cin) . . . . int operator void *() Converts an ios object to a pointer so that it can be compared to 0. The conversion returns a nonzero value (not meant for further use) if neither failbit nor badbit is set in the error state. This allows the use of such expressions as if (cin) . . . and if (cin >> x) . . . . 4-38 iostream Package ios class Other Member Functions int bad() const Returns a nonzero value if badbit is set in the error state; otherwise, it returns 0. This usually indicates that some operation on rdbuf() has failed, and that continued operations on the associated streambuf object may not be possible. long bitalloc() Returns a long integer with a single, previously unallocated bit set. This gives you an additional flag should you need one (to pass to ios::set(), for example). void clear(int state) Stores an integer value as the error state. A 0 value clears all bits. int eof() const Returns a nonzero value if eofbit is set in the error state; otherwise, it returns 0. This bit is usually set during an extraction and when an end-of-file has been encountered. int fail() const Returns a nonzero value if either badbit or failbit is set in the error state; otherwise, it returns 0. This usually indicates that some extraction or conversion operation has failed, but that the stream remains usable; once failbit clears, operations on the stream can usually continue. char fill() const Returns the variable currently used as the fill (padding) character. char fill(char c) Sets c as the fill (padding) character if one is needed (see width ()) and returns the previous value. The default fill character is a space. The right, left, and internal flags determine positioning of the fill character. A parameterized manipulator, setfill, is also available for setting the fill character. iostream Package 4-39 ios class long flags() const Returns the current format flags. long flags(long f) Resets all the format flags to those specified in f and returns the previous settings. The flags are as follows: skipws For scalar operations, instructs the arith- metical extractor to skip white space before beginning conversion. As a precaution against looping, arithmetical extractors signal an error if the next character is white space and the skip variable is not set. left Control padding of values. The left flag right adds a fill character after a value, right internal adds a fill character before a value, and internal adds a fill character after any leading sign or base indication, but before the value. Right-adjustment is the default if none of these flags are set. The fields are collectively identified by the static member ios::adjustfield. The fill character is controlled by the fill() function and the width after the padding is controlled by the width() function. dec Control the conversion base of a value. oct Insertions are in decimal if none of these hex flags are set. Extractions follow C++ lexical conventions for integral constants. The flags are collectively identified by the static member ios::basefield. The manipulators hex, dec, and oct are also available for setting the conversion base. showbase Converts insertions to an external form that can be read according to the C++ lexical conventions for integral constants. By default, showbase is not set. showpos Inserts a plus sign (+) into a decimal conversion of a positive integral value. 4-40 iostream Package ios class uppercase Uses an uppercase X for hexadecimal conversion when showbase is set, or uses uppercase E to print floating-point numbers in scientific notation. By default, uppercase is not set. showpoint Specifies that trailing zeros and decimal points appear in the result of a floating-point conversion. scientific Control the format to which a floating-point value is converted for insertion into a stream. fixed These two flags are collectively identified by the static member ios::floatfield. The scientific flag converts the value using scientific notation, with one digit before the decimal point. Depending on the uppercase flag, an E or an e introduces the exponent. The fixed flag converts the value to decimal notation. For both flags, the precision function determines the number of digits following the decimal point (6 is the default). If neither flag is set, then scientific notation is used only if the exponent from the conversion is less than -4 or greater than the precision. If showpoint is not set, trailing zeros are removed from the result and a decimal point appears only if followed by a digit. unitbuf Causes ostream::osfx() to perform a flush af- ter each insertion. Unit buffering constitutes a performance compromise between buffered and unbuffered output. stdio Causes ostream::osfx() to flush stdout and stderr after each insertion. int good() const Returns a nonzero value if the error state has no bits set; otherwise, it returns 0. void init(streambuf *b) Initializes the ios object; intended for use by classes derived from ios. iostream Package 4-41 ios class long& iword(int i) Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc. [1] int precision() const Returns the precision format state variable. int precision(int i) Sets the precision format state variable to i and returns the previous value. The variable controls the number of significant digits inserted by the floating-point inserter. The default is 6. A parameterized manipulator, setprecision, is also available for setting the precision. void *&ios::pword(int i) Returns a reference to the ith user-defined word, where i is an index into an array of words allocated by ios::xalloc. This function differs from iword() only in type. streambuf *ios::rdbuf() Returns a pointer to the streambuf object that was associated with an ios object when the ios object was constructed. int rdstate() const Returns the current error state. long setf(long setbits) Makes available to the streambuf object associated with an ios object the format flags marked in setbits and returns the previous settings. A parameterized manipulator, setiosflags, performs the same function. If you are setting a flag that is part of a collection (for example, basefield), note that this manipulator does not clear the other flags in the collection. ___________________ [1]This function references a single array that is shared among all instances of ios objects. This differs from the Digital UNIX operating system, where this function references the array that is specific to the ios instance. 4-42 iostream Package ios class long setf(long setbits, long field) Clears, in the streambuf object associated with an ios object, the format flags specified by field, then resets these flags to the settings marked in setbits. It returns the previous settings. Specifying 0 in setbits clears all the bits specified in field, as does the parameterized manipulator, resetioflags. void setstate(int state) Changes only the bits specified in the state argument. void sync_with_stdio() Solves problems that arise with mixing stdio and iostream objects. When first called, the sync_with_stdio() function resets the standard iostream functions (cin, cout, cerr, and clog) to be streams using stdiobuf objects. Subsequently, input and output using these streams may be mixed with input and output using the corresponding FILE parameters (stdin, stdout, and stderr), and properly synchronized. The sync_with_stdio() function makes cout and cerr unit buffered (see ios::unitbuf and ios::stdio). Invoking sync_with_stdio() degrades performance variably; the shorter the strings being inserted, the greater the degradation. ostream *ios::tie() const Returns the tie variable (see the following member function description). ostream *ios::tie(ostream *osp) Sets the tie variable to osp and returns its previous value. The tie variable supports automatic flushing of ios objects. The ios object that the tie variable points at is flushed if the variable is not null, and an ios object either needs more characters or has characters to be consumed. By default, cin is initially tied to cout so that attempts to get more characters from standard input result in flushing standard output. Additionally, cerr and clog are tied to cout by default. By default, the tie variable is set to 0 for other ios objects. iostream Package 4-43 ios class long unsetf(long setbits) Unsets, in the streambuf object associated with an ios object, the bits set in setbits; it returns the previous settings. int width() const Returns the field-width format variable (see the following member function description). The field width setting within the ios class is ignored during single character output: operator<<(char) and operator<<(unsigned char). int width(int n) Sets the field-width format variable to n and returns the previous value. The field width specifies a minimum number of characters for inserters. When the variable is 0 (the default), inserters insert only as many characters as needed to represent the value being inserted. When the variable is nonzero, and the value being inserted needs fewer than field-width characters to be represented, inserters insert at least that many characters using the fill character to pad the value. Numeric inserters do not truncate values even if the value being inserted is more than field-width characters. After each insertion or extraction, the field-width format variable resets to 0. A parameterized manipulator, setw, is also available for setting the field width. int xalloc() Returns a previously unused index into an array of words available for use by derived classes as format state variables. [1] ___________________ [1]This function references a single array that is shared among all instances of ios objects. This differs from the Digital UNIX operating system, where this function references the array that is specific to the ios instance. 4-44 iostream Package ios class Examples 1. cout.width(6); cout << x << " " << y; Outputs x in at least six characters, but uses only as many characters as needed for the separating space and y. In the following examples, mystrm is an ios object. 2. mystrm.clear(ios::badbit|s.rdstate()) Sets the badbit member of the io_state enumerated data type without clearing previously set bits. 3. mystrm.setf(ios::hex,ios::basefield) Changes the conversion base in mystrm to be hexadeci- mal. iostream Package 4-45 iostream class ________________________________________________________________ iostream class Provides the means to both insert into and extract from a single sequence of characters. Header File #include Alternative Header #include Declaration class iostream: public istream, public ostream { public: iostream(streambuf *); virtual ~iostream(); protected: iostream(); }; Description This class combines the istream and ostream classes. You use it to carry out bidirectional operations (inserting into and extracting from a single sequence of characters). Constructors and Destructors iostream() Constructs an iostream object, in undefined form, to enable inheritance by derived classes. iostream(streambuf *b) Constructs an iostream object. It initializes ios state variables and associates the iostream object with the streambuf object pointed to by b. 4-46 iostream Package iostream class virtual ~iostream() Deletes an iostream object. iostream Package 4-47 iostream_withassign class ________________________________________________________________ iostream_withassign class Adds an assignment operator and a constructor with no operands to the iostream class. Header File #include Alternative Header #include Declaration class iostream_withassign: public iostream { public: iostream_withassign(); virtual ~iostream_withassign(); iostream_withassign &operator=(iostream &); iostream_withassign &operator=(streambuf *); }; Description This class adds an assignment operator and a constructor with no operands to the iostream class. Constructors and Destructors iostream_withassign() Constructs an iostream_withassign object; it does no initialization. virtual ~iostream_withassign() Deletes an iostream_withassign object; no user action is required. 4-48 iostream Package iostream_withassign class Overloaded Operators iostream_withassign &operator = (iostream &) Associates iostream->rdbuf() with an iostream_withassign object and initializes the entire state of that object. iostream_withassign &operator = (streambuf *) Associates streambuf* with an iostream_withassign object and initializes the entire state of that object. iostream Package 4-49 istream class ________________________________________________________________ istream class Supports interpretation of characters extracted from an associated streambuf object. Header File #include Alternative Header #include Declaration class istream : virtual public ios { public: istream(streambuf *); virtual ~istream(); inline int gcount(); istream &get(char *ptr, int len, char delim = '\n'); istream &get(unsigned char *ptr, int len, char delim = '\n'); istream &get(char &); inline istream &get(unsigned char &); istream &get(streambuf &sb, char delim = '\n'); int get(); istream &getline(char *ptr, int len, char delim = '\n'); istream &getline(unsigned char *ptr, int len, char delim = '\n'); istream &ignore(int len = 1, int delim = ); int ipfx(int need = 0); void isfx(); int peek(); istream &putback(char); istream &read(char *s, int n); inline istream &read(unsigned char *s, int n); 4-50 iostream Package istream class istream &seekg(streampos); istream &seekg(streamoff, seek_dir); void skipwhite(); int sync(); streampos tellg(); istream &operator>>(char *); istream &operator>>(char &); istream &operator>>(short &); istream &operator>>(int &); istream &operator>>(long &); istream &operator>>(float &); istream &operator>>(double &); istream &operator>>(unsigned char *); istream &operator>>(unsigned char &); istream &operator>>(unsigned short &); istream &operator>>(unsigned int &); istream &operator>>(unsigned long &); istream &operator>>(streambuf *); inline istream &operator>>(istream &(*f)(istream &)); istream &operator>>(ios &(*f)(ios &)); protected: istream(); }; Description This class provides facilities for formatted and unformatted extraction from streambuf objects. Constructors and Destructors istream(streambuf *sb) Constructs an istream object. It initializes ios state variables and associates the istream object with the buffer pointed to by sb. virtual ~istream() Deletes an istream object. iostream Package 4-51 istream class Overloaded Operators The following operators are all formatted input extrac- tors. Given the expression ins >> x, these operators extract characters from ins and convert them to the variable x. The argument to the operator determines the type of x. Extractions are performed only if a call to ipfx(0) returns a nonzero value. Errors are indicated by setting the error state of ins. ios::failbit means that characters in ins did not represent the required type. ios::badbit means that attempts to extract characters failed. ins is always returned. The details of conversion depend on the values of the ins object format state flags and variables, and the type of x. Extractions that use width reset it to 0; otherwise, the extraction operators do not change the value of the istream object format state. istream &operator >> (char &x) istream &operator >> (unsigned char &x) Extracts a character and stores it in x. istream &operator >> (char *x) istream &operator >> (unsigned char *x) Extracts characters and stores them in the array pointed at by x, until a white-space character is found in the iostream object. The action leaves the terminating white- space character in the iostream object. If the iostream object's width() is nonzero, it is taken to be the size of the array and no more than width()-1 characters are extracted. A terminating null character ('\0') is always stored, even if nothing else is done because of the iostream object's error state. The iostream object's width() is reset to 0. istream &operator >> (short &x) istream &operator >> (int &x) istream &operator >> (long &x) istream &operator >> (unsigned short &x) istream &operator >> (unsigned int &x) 4-52 iostream Package istream class istream &operator >> (unsigned long &x) Extracts characters and converts them to an integral value according to the conversion specified in the iostream object's format flags. Converted values are stored in x. The first character can be a sign (- or +). After that, the conversion is octal if ios::oct is set in the iostream object's flags, decimal if ios::dec is set, or hexadecimal if ios::hex is set. The first nondigit that is left in the iostream object terminates the conversion. If no conversion base flag is set, the conversion proceeds according to C++ lexical conventions: if the first characters (after the optional sign) are 0x or 0X, the conversion is hexadecimal; if the first character is 0, the conversion is octal; otherwise, the conversion is decimal. If no digits are available (not counting the 0 in 0x or 0X during hex conversion), ios::failbit is set. istream &operator >> (float &x) istream &operator >> (double &x) Extracts characters and converts them according to C++ syntax for a float value or a double value. Converted values are stored in x. If no digits are available in the iostream object, or if the iostream object does not begin with a well formed floating-point or double number, ios::failbit is set. istream &operator >> (streambuf *b) Keeps getting characters from ios and inserting them into the buffer b until EOF is reached, if ios::ipfx(0) returns nonzero. Always returns the iostream object. istream &operator >> (ios &(*f)(ios &)) Calls an ios object manipulator function f for an istream object. istream &operator >> (istream &(*f)(istream &)) Calls an istream object manipulator function f for an istream object. iostream Package 4-53 istream class Other Member Functions The unformatted input extractors, get, getline, ignore, and read, are among these functions. Before performing any extractions, these extractors, plus the unformatted function peek (which returns the next character without extracting it), call ipfx(1) and proceed only if a nonzero value is returned. int gcount() Returns the number of characters extracted by the last unformatted input function (get, getline, ignore, and read). Note that formatted input functions can call unformatted input functions and also reset this number. int get() Extracts a character and returns it, or returns EOF if the extraction encounters the end-of-file. It never sets ios::failbit. istream &get(char &ptr) istream &get(unsigned char &ptr) Extracts a single character and stores it in &ptr. istream &get(char *ptr, int len, char delim) istream &get(unsigned char *ptr, int len, char delim) Extracts characters and stores them in the byte array beginning at ptr and extending for len bytes. Extraction stops when any of the following conditions are met: o The extractor encounters delim (delim is left in the istream object and not stored.) o The istream object has no more characters. o The array has only one byte left. The function stores a terminating null, even if it does not extract any characters because of its error status. The extraction sets ios::failbit only if it reaches an end-of-file before storing any characters. 4-54 iostream Package istream class istream &get(streambuf &sb, char delim) Extracts characters from an istream object rdbuf() function and stores them into sb. It stops if it encounters the end-of-file, if a store into sb fails, or if it encounters delim (which it leaves in the istream object). The function sets ios::failbit if the extraction stops because the store operation into sb fails. istream &getline(char *ptr, int len, char delim) istream &getline(unsigned char *ptr, int len, char delim) Functions the same as get(char *, int, char) except that these extract a terminating delim character from an istream object. If delim occurs when exactly len characters have been extracted, a filled array is considered to be the cause of the termination and the extraction leaves this delim in the istream object. istream &ignore(int len, int delim) Extracts and discards up to len characters. Extraction stops prematurely if delim is extracted or the end-of- file is reached. If delim is EOF, it can never cause termination. int ipfx(int need) Returns 0 if the error state of an istream object is nonzero. If necessary (and if it is not null), the function flushes any ios tied to the istream object (see the description of ios::tie()). Flushing is considered necessary if need is set to 0 or if fewer than need characters are immediately available. If ios::skipws is set in the istream object's flags() function, and need is 0, then the function extracts the leading white-space characters from the istream object. The function returns 0 if an error occurs while skipping white space; otherwise, it returns a nonzero value. void isfx() Performs input suffix operations (used for internal processing). iostream Package 4-55 istream class int peek() Begins by calling ipfx(1). If that call returns 0, or if the istream object is at the end-of-file, the function returns EOF. Otherwise, it returns the next character without extracting it. istream &putback(char c) Tries to back up an istream object rdbuf() function. c must be the character before the get pointer belonging to the istream object rdbuf(). (Unless some other activity is modifying the istream object rdbuf(), this is the last character extracted from the istream object.) If c is not the character before the get pointer, the effect of the function is undefined; the backup may fail and set the error state. The putback function is a member of the istream object, but it never extracts characters so it does not call ipfx. However, it returns without doing anything if the error state is nonzero. istream &read(char *s, int n) istream &read(unsigned char *s, int n) Extracts n characters and stores them in the array begining at s. If it reaches the end-of-file before extracting n characters, the function stores whatever it can extract and sets ios::failbit. To determine the number of characters extracted, use the istream gcount() function. istream &seekg(streampos) istream &seekg(streamoff, seek_dir) Repositions the get pointer of an istream object rdbuf() function. int sync() Establishes consistency between internal data structures and the external source of characters. Calls an istream object rdbuf()->sync(), which is a virtual function, so the details depend on the derived class. Returns EOF to indicate errors. void skipwhite() Skips extracted white-space characters. 4-56 iostream Package istream class streampos tellg() Returns the current position of the get pointer of an istream object rdbuf() function. Examples 1. char c; cin.get(c); Extracts a single character from cin. 2. tmp.seekg(10,ios::cur) Moves the point in a file from which information is read forward 10 bytes. See Also ios class istream_withassign class istrstream class iostream Package 4-57 istream_withassign class ________________________________________________________________ istream_withassign class Adds an assignment operator and a constructor with no operands to the istream class. Header File #include Alternative Header #include Declaration class istream_withassign: public istream { public: istream_withassign(); virtual ~istream_withassign(); istream_withassign &operator=(istream &); istream_withassign &operator=(streambuf *); }; Description This class adds an assignment operator and a constructor with no operands to the istream class. Constructors and Destructors istream_withassign() Constructs an istream_withassign object; it does no initialization. virtual ~istream_withassign() Deletes an istream_withassign object; no user action is required. 4-58 iostream Package istream_withassign class Overloaded Operators istream_withassign &operator = (istream &s) Associates an istream object's rdbuf() function with an istream_withassign object and initializes the entire state of that object. istream_withassign &operator = (streambuf *sb) Associates sb with an istream_withassign object and initializes the entire state of that object. iostream Package 4-59 istrstream class ________________________________________________________________ istrstream class Specializes the istream class to perform extractions from arrays of bytes in memory. Header File #include Alternative Header #include Declaration class istrstream: public istream { public: istrstream(char *); istrstream(char *, int); strstreambuf *rdbuf(); }; Description Objects of this class perform in-core extractions from arrays of bytes in memory. Constructors and Destructors istrstream(char *cp) Constructs an istrstream object and fetches characters from the (null terminated) string cp. The terminating null character does not become part of the sequence. Seeks (istream::seekg()) are permitted within the allocated space. istrstream(char *cp, int len) Constructs an istrstream object and fetches characters from the array beginning at cp and extending for len bytes. Seeks (istream::seekg()) are permitted anywhere within that array. 4-60 iostream Package istrstream class Member Function strstreambuf *rdbuf() Returns the strstreambuf object associated with the istrstream object. iostream Package 4-61 OAPP(TYPE) class ________________________________________________________________ OAPP(TYPE) class For an ostream object, declares predefined parameterized applicators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the ostream object. It must be an identifier. Declaration class OAPP(TYPE) { public: OAPP(TYPE)(ostream &(*f)(ostream &, TYPE)); OMANIP(TYPE) operator()(TYPE a); }; Constructor OAPP(TYPE)(ostream &(*f)(ostream &, TYPE)) Creates an applicator. Operator OMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an ostream object. 4-62 iostream Package OAPP(TYPE) class See Also OMANIP(TYPE) class iostream Package 4-63 ofstream class ________________________________________________________________ ofstream class Supports output to files. Header File #include Alternative Header #include Declaration class ofstream: public ostream { public: ofstream(); ofstream(const char *name, int mode = ios::out, int prot = filebuf::openprot); ofstream(int fd); ofstream(int fd, char *p, int len); ~ofstream(); void attach(int fd); void close(); void open(const char *name, int mode = ios::out, int prot = filebuf::openprot); filebuf *rdbuf(); void setbuf(char *p, int len); }; Description This class specializes the ostream class to files using a filebuf object to do the output. Your program can perform common operations, such as opening and closing files, without explicitly mentioning filebuf objects. 4-64 iostream Package ofstream class Constructors and Destructors ofstream() Constructs an unopened ofstream object. ofstream(int fd) Constructs an ofstream object connected to a file whose descriptor is passed through the fd argument. The file must already be open. ofstream(int fd, char *p, int len) Constructs an ofstream object connected to a file whose descriptor is passed through the fd argument, and also initializes the associated filebuf object to use the len bytes starting at p as the reserve area. If p is null or len is 0, the filebuf object is unbuffered. ofstream(const char *name, int mode, int prot) Constructs an ofstream object and opens the file specified by the name argument. The mode and prot arguments specify the file open mode and protection. By default, prot is filebuf::openprot. If the open fails, the error state (io_state) of the constructed ofstream object indicates failure. ~ofstream() Deletes an ofstream object. Member Functions void attach(int fd) Connects an ofstream object to a file whose descriptor is passed through the fd argument. A failure occurs when the ifstream object is connected to a file, in which case ios::failbit is set in the ofstream object error state. void close() Closes any associated filebuf object and consequently breaks the connection of the ofstream object to the file. The error state of the ofstream object is cleared except on failure. A failure occurs when the call to the filebuf object close() function fails. iostream Package 4-65 ofstream class void open(const char *name, int mode, int prot) Opens a file specified by the name argument and connects the ofstream object to it. If the file does not exist, the function tries to create it with the protection specified by the prot argument unless ios::nocreate is set. By default, prot is filebuf::openprot. Failure occurs if the ofstream object is open or when the call to the filebuf object open() function fails, in which case ios::failbit is set in the filebuf object's error state. The members of open_mode are bits that may be joined together by or (and because this joining takes an int, open() takes an int rather than an open_mode argument). For an explanation of the meanings of these bits in open_mode, see the Enumerated Types section for the ios class. filebuf *rdbuf() Returns a pointer to the filebuf object associated with the ofstream object. This function has the same meaning as ios::rdbuf(), but has a different type. void setbuf(char *p, int len) Calls the associated filebuf object setbuf() function to request space for a reserve area. A failure occurs if the filebuf object is open or if the call to rdbuf()->setbuf fails for any other reason. 4-66 iostream Package OMANIP(TYPE) class ________________________________________________________________ OMANIP(TYPE) class For an ostream object, declares predefined parameterized manipulators and provides macros for user-defined parameterized manipulators. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the ostream object. It must be an identifier. Declaration class OMANIP(TYPE) { public: OMANIP(TYPE)(ostream &(*f)(ostream &, TYPE), T a ); friend ostream &operator<<(ostream & s, OMANIP(TYPE) &m); }; Description These manipulators serve the ostream class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the ostream class. In its simplest form, a manipulator takes an ostream& argument, operates on it in some way, and returns it. iostream Package 4-67 OMANIP(TYPE) class Constructor OMANIP(TYPE)(ostream &(*f)(ostream &, TYPE), T a ) Creates a manipulator. Operator ostream &operator << (ostream & s, OMANIP(TYPE) &m) Sends data to an ostream object. 4-68 iostream Package ostream class ________________________________________________________________ ostream class Supports insertion into streambuf objects. Header File #include Alternative Header #include Declaration class ostream : virtual public ios { public: ostream(streambuf *); virtual ~ostream(); ostream &flush(); int opfx(); void osfx(); ostream &put(char c); ostream &seekp(streampos); ostream &seekp(streamoff, seek_dir); streampos tellp(); ostream &write(const char *ptr, int n); inline ostream &write(const unsigned char *ptr, int n); ostream &operator<<(const char *); ostream &operator<<(char); inline ostream &operator<<(short); ostream &operator<<(int); ostream &operator<<(long); ostream &operator<<(float); ostream &operator<<(double); ostream &operator<<(const unsigned char *); inline ostream &operator<<(unsigned char); inline ostream &operator<<(unsigned short); ostream &operator<<(unsigned int); ostream &operator<<(unsigned long); ostream &operator<<(void *); iostream Package 4-69 ostream class ostream &operator<<(streambuf *); inline ostream &operator<<(ostream &(*f)(ostream &)); ostream &operator<<(ios &(*f)(ios &)); protected: ostream(); }; Description Objects of this class perform formatted and unformatted insertions into streambuf objects. Constructors and Destructors ostream(streambuf *b) Constructs an istream object. It initializes ios state variables and associates the buffer b with the ostream object. virtual ~ostream() Deletes an ostream object. Overloaded Operators The following operators are all formatted output inserters. Given the expression outs << x, these operators insert into outs.rdbuf() a sequence of characters representing x. The argument to the operator determines the type of x. Insertions are performed after a call to outs.opfx() only if that call returns nonzero. Errors are indicated by setting the error state of the ostream object. The ostream object is always returned. Conversion of x to a sequence of characters depends on the type of x and on the values of the ostream object's format state flags and variables. Padding occurs after this representation is determined. If width() is greater than 0, and the representation contains fewer than width() characters, then the function adds enough fill() characters to bring the total number of characters to ios::width(). If ios::left() is set, the sequence is left-adjusted; that is, the function puts the padding after the sequence of characters. If ios::right() is set, the padding is added before the character sequence. If 4-70 iostream Package ostream class ios::internal() is set, the padding is added after any leading sign or base indication and before the characters that represent the value. ios::width() is reset to 0 but all other format variables are unchanged. The full sequence (padding plus representation) is inserted into the ostream object rdbuf() function. ostream &operator << (char x) ostream &operator << (unsigned char x) Inserts a character x. No special conversion is needed. ostream &operator << (const char *x) ostream &operator << (const unsigned char *x) Inserts a sequence of characters up to (but not including) the terminating null of the string that x points at. ostream &operator << (short x) ostream &operator << (int x) ostream &operator << (long x) ostream &operator << (unsigned short x) ostream &operator << (unsigned int x) ostream &operator << (unsigned long x) Inserts characters as follows: o If x is positive, the representation contains a sequence of octal digits if ios::oct is set in the ios object format flags, decimal digits if ios::dec is set, or hexadecimal digits if ios::hex is set. If none of these flags are set, the conversion defaults to decimal. o If x is negative, decimal conversion includes a minus sign (-) followed by decimal digits. o If x is positive and ios::showpos is set, decimal conversion includes a plus sign (+) followed by decimal digits. o Conversions other than decimal treat all values as unsigned. o If ios::showbase is set, the hexadecimal representation contains 0x before the hexadecimal digits or 0X if ios::uppercase is set; the octal representation contains a leading 0. iostream Package 4-71 ostream class ostream &operator << (float x) ostream &operator << (double x) Converts the arguments according to the current values of the ostream object's precision() function, the ostream object's width() function, and the ostream object's format flags: ios::scientific, ios::fixed, and ios::uppercase. The default value for the ostream object's precision() function is 6. If neither ios::scientific nor ios::fixed is set, the value of x determines whether the representation uses scientific or fixed notation. ostream &operator << (void *v) Converts pointers to integral values and then converts them to hexadecimal numbers as if ios::showbase was set. ostream &operator << (streambuf *sb) Given the expression outs << sb, inserts into sb.rdbuf() the sequence of characters that can be fetched from sb. When no more characters can be fetched from sb, insertion stops. This function does no padding. It always returns the ostream object. ostream &operator << (ios &(*f)(ios &)) Calls an ios object manipulator function f for an ostream object. ostream &operator << (ostream &(*f)(ostream &)) Calls an ostream object manipulator function f for an ostream object. Other Member Functions ostream &flush() Calls the ostream object's rdbuf()->sync() function to consume (that is, write to the external file) any characters that may have been stored into a streambuf object but are not yet consumed. int opfx() Performs output prefix actions. If the error state of the ostream object is nonzero, it returns immediately. If the value of the ostream object's tie() function is not null, it is flushed. The function returns nonzero except when the error state of the ostream object is nonzero. 4-72 iostream Package ostream class void osfx() Performs output suffix actions before returning from inserters. If ios::unitbuf is set, this function flushes the ostream object. If ios::stdio is set, the function flushes stdout and stderr. It is called by all predefined inserters, and should also be called by user-defined inserters after any direct manipulation of the streambuf object. It is not called by the binary output functions. ostream &ostream::put(char c) Inserts c into the ostream object's rdbuf() function. It sets the error state if the insertion fails. ostream &seekp(streampos) ostream &seekp(streamoff, seek_dir) Repositions the put pointer of the ostream object's rdbuf() function. streampos tellp() Returns the current position of the put pointer belonging to the ostream object's rdbuf() function. ostream &write(const char *ptr, int n) ostream &write(const unsigned char *ptr, int n) Inserts the n characters starting at ptr into the ostream object's rdbuf() function. These characters may include zeros; that is, ptr need not be a null-terminated string. Example char c = 'Z'; cout.put(c); Inserts a single character (Z) into cout. See Also ostream_withassign class ostrstream class iostream Package 4-73 ostream_withassign class ________________________________________________________________ ostream_withassign class Adds an assignment operator and a constructor with no operands to the ostream class. Header File #include Alternative Header #include Declaration class ostream_withassign: public ostream { public: ostream_withassign(); virtual ~ostream_withassign(); ostream_withassign &operator=(ostream &); ostream_withassign &operator=(streambuf *); }; Description This class adds an assignment operator and a constructor with no operands to the ostream class. Constructors and Destructors ostream_withassign() Constructs an ostream_withassign object; it does no initialization. virtual ~ostream_withassign() Deletes an ostream_withassign object; no user action is required. 4-74 iostream Package ostream_withassign class Overloaded Operators ostream_withassign &operator = (ostream &s) Associates s.rdbuf() with the ostream_withassign object and initializes the entire state of that object. ostream_withassign &operator = (streambuf *sb) Associates sb with an ostream_withassign object and initializes the entire state of that object. iostream Package 4-75 ostrstream class ________________________________________________________________ ostrstream class Supports the insertion of characters into arrays of bytes in memory. Header File #include Alternative Header #include Declaration class ostrstream: public ostream { public: ostrstream(); ostrstream(char *, int, int = ios::out); ~ostrstream(); int pcount(); strstreambuf *rdbuf(); char *str(); }; Description This class specializes the ostream class for in-core operations by providing members that insert characters into arrays of bytes in memory. Constructors and Destructors ostrstream() Constructs an ostrstream object and dynamically allocates space to hold stored characters. 4-76 iostream Package ostrstream class ostrstream::ostrstream(char *cp, int n, int mode) Constructs an ostrstream object and stores characters into the array starting at cp and continuing for n bytes. If ios::ate or ios::app is set in mode, the function takes cp to be a null-terminated string and it begins storing at the null character; otherwise, it begins storing at cp. Seeks are allowed anywhere in the array. ~ostrstream() Deletes an ostrstream object. Member Functions int pcount() Returns the number of bytes that have been stored into the buffer. This function is useful when binary data has been stored and the ostrstream object str() function does not point to a null-terminated string. strstreambuf *rdbuf() Returns the strstreambuf associated with the ostrstream object. char *str() Returns a pointer to the array being used and freezes the array. After str() has been called, the effect of storing more characters into the strstream object is undefined. If the strstream object was constructed with an explicit array, the function returns a pointer to the array; otherwise, it returns a pointer to a dynamically allocated area. Until str() is called, deleting the dynamically allocated area is the responsibility of the strstream object. After str() returns, dynamic allocation becomes the responsibility of the user program. Example char *bptr = bf.str() Initializes the variable bptr with the address of the array associated with the ostrstream object bf. This lets you manipulate the array through bptr just as you would any character array. iostream Package 4-77 SAPP(TYPE) class ________________________________________________________________ SAPP(TYPE) class Defines parameterized applicators for an ios object. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the ios object. It must be an identifier. Declaration class SAPP(TYPE) { public: SAPP(TYPE)(ios &(*f)(ios &, TYPE)); SMANIP(TYPE) operator()(TYPE a); }; Constructor SAPP(TYPE)(ios &(*f)(ios &, TYPE)) Creates an applicator. Operator SMANIP(TYPE) operator () (TYPE a) Casts an object of type a into a manipulator function for an istream or ostream object. See Also SMANIP(TYPE) class 4-78 iostream Package SMANIP(TYPE) class ________________________________________________________________ SMANIP(TYPE) class Defines parameterized manipulators for an ios object. Header File #include Alternative Header #include Compile-Time Parameter TYPE-The type of the ios object. It must be an identifier. Declaration class SMANIP(TYPE) { public: SMANIP(TYPE)(ios &(*f)(ios &, TYPE), TYPE a); friend istream &operator>>(istream &i, SMANIP(TYPE) &m); friend ostream &operator<<(ostream &o, SMANIP(TYPE) &m); }; Description These manipulators serve the ios class by producing some useful effect, such as embedding a function call in an expression containing a series of insertions and extractions. You also can use manipulators to shorten the long names and sequences of operations required by the ios class. In its simplest form, a manipulator takes an ios& argument, operates on it in some way, and returns it. iostream Package 4-79 SMANIP(TYPE) class Constructor SMANIP(TYPE)(ios &(*f)(ios &, TYPE), TYPE a) Creates a manipulator. Operators ostream &operator << (ostream &o, SMANIP(TYPE) &m) Sends data to an ostream object. istream &operator >> (istream &i, SMANIP(TYPE) &m) Takes data from an istream object. 4-80 iostream Package stdiobuf class ________________________________________________________________ stdiobuf class Provides input/output facilities through stdio FILE. Header File #include Alternative Header #include Declaration class stdiobuf: public streambuf { public: stdiobuf(FILE *f); virtual int overflow(int = ); virtual streampos seekoff(streamoff, seek_dir, int mode); FILE *stdiofile(); virtual int sync(); virtual int underflow(); }; Description This class specializes the streambuf class for stdio FILE. It uses unbuffered mode causing all operations to be reflected immediately in the stdio FILE. Constructor stdiobuf(FILE *f) Constructs an empty stdiobuf object and connects it to the stdio FILE that the argument f points to. iostream Package 4-81 stdiobuf class Member Functions virtual int overflow(int c) Called to consume characters. If c is not EOF, this function must also either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr(), call setp() to establish a new put area, and (if c != EOF) store c using sputc(). The overflow(c) function should return EOF to indicate an error; otherwise, it should return something else. virtual streampos seekoff(streamoff off, seek_dir dir, int mode) Repositions the abstract get and put pointers (not pptr() and gptr()). mode specifies whether to modify the put pointer (ios::out bit set), the get pointer, or both (ios::in bit set). off is interpreted as a byte offset. For the meanings of dir, see the explanation of the enumerated type seek_dir in class ios. A class derived from streambuf is not required to support repositioning. If the derived class does not, then seekoff() should return EOF. If the derived class does support repositioning, seekoff() should return the new position or EOF on error. FILE *stdiofile() Returns a pointer to the stdio FILE associated with the stdiobuf object. virtual int sync() Should consume any characters stored into the put area and, if possible, give back to the source any characters in the get area that have not been fetched. When sync() returns, there should be no unconsumed characters and the get area should be empty. If some kind of failure occurs, the function should return EOF. 4-82 iostream Package stdiobuf class virtual int underflow() Called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area. iostream Package 4-83 stdiostream class ________________________________________________________________ stdiostream class Specializes the iostream class for stdio FILE. Header File #include Alternative Header #include Declaration class stdiostream: public iostream { public: stdiostream(FILE *f); ~stdiostream(); stdiobuf *rdbuf(); }; Description This class specializes the iostream class for stdio FILE, and causes that class to use a stdiobuf object as its associated streambuf object. In most other existing implementations, the stdiostream class is derived directly from the ios class rather than from the iostream class. Deriving the stdiostream class from the ios class limits its usefulness and, therefore, can be considered a historical mistake. Nevertheless, for maximum portability, you should use only those stdiostream features that originate from the ios class and avoid the features supplied by the iostream class. 4-84 iostream Package stdiostream class Constructors and Destructors stdiostream(FILE *f) Constructs a stdiostream object whose stdiobuf object is associated with the FILE parameter that the f argument points to. ~stdiostream() Deletes a stdiostream object and closes the associated stdiobuf object. iostream Package 4-85 stdiostream class Member Function stdiobuf *rdbuf() Returns a pointer to the stdiobuf object associated with the stdiostream object. 4-86 iostream Package streambuf class ________________________________________________________________ streambuf class Provides the buffer mechanism for streams. Header File #include Alternative Header #include Declaration class streambuf { public: streambuf(); streambuf(char *p, int len); virtual ~streambuf(); void dbp(); protected: int allocate(); char *base(); int blen(); virtual int doallocate(); char *eback(); char *ebuf(); char *egptr(); char *epptr(); void gbump(int n); char *gptr(); char *pbase(); void pbump(int n); char *pptr(); void setb(char *b, char *eb, int a = 0); void setg(char *eb, char *g, char *eg); void setp(char *p, char *ep); int unbuffered(); void unbuffered(int n); iostream Package 4-87 streambuf class public: int fd(); void fd(int); FILE *fp(); void fp(FILE *); int in_avail(); int out_waiting(); virtual int overflow(int c = EOF); virtual int pbackfail(int c); int sbumpc(); virtual streampos seekpos(streampos, int = ios::in | ios::out); virtual streampos seekoff(streamoff, seek_dir, int = ios::in | ios::out); virtual streambuf *setbuf(char *ptr, int len); streambuf *setbuf(unsigned char *ptr, int len); streambuf *setbuf(char *ptr, int len, int i); int sgetc(); int sgetn(char *ptr, int n); int snextc(); int sputbackc(char c); int sputc(int c = EOF); int sputn(const char *s, int n); void stossc(); virtual int sync(); virtual int underflow(); }; Description This class supports buffers into which you can insert (put) or extract (get) characters. It contains only the basic members for manipulating the characters. Also, several of its member functions are virtual; to implement virtual functions, you typically use a class derived from the streambuf class. The protected members of the streambuf class present an interface to derived classes organized around the get, put, and reserve areas (arrays of bytes), which are managed cooperatively by the base and derived classes. 4-88 iostream Package streambuf class The reserve area is a sequence of characters with an associated get pointer, put pointer, or both. This area serves mainly as a resource in which to allocate space for the put and get areas. As characters enter and exit the reserve area, the put and get areas change but the reserve area remains fixed. A collection of character pointer values defines the three areas. These pointers infer a boundary condition; therefore, it may be helpful to consider such pointers as pointing just before the byte, even though they point directly at it. Classes derived from streambuf vary in their handling of the get and put pointers. The simplest are unidirectional buffers that permit only get and put operations. Such classes serve as producers and consumers of characters. Queue-like buffers (such as strstream and strstreambuf) have a put and a get pointer that move independently of each other. In such buffers, stored characters are queued until later fetched. File-like buffers (such as filebuf) allow both get and put operations but have their get and put pointers linked together, so that when one pointer moves so does the other. You can call virtual functions to manage the collections of characters in the get and put areas. Services supplied by virtual functions include fetching more characters from an ultimate producer and flushing a collection of characters to an ultimate consumer. If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer. Data Member void dbp() Writes directly on file descriptor 1 information in ASCII about the state of the buffer. It is intended for debugging and nothing is specified about the form of the output. What it prints out can be understood only in relation to the protected interface, but dbp() is a public domain function so that it can be called anywhere during debugging. iostream Package 4-89 streambuf class Constructors and Destructors streambuf() Constructs an empty buffer corresponding to an empty sequence. streambuf(char* base, int length) Constructs an empty buffer and then sets up the reserve area to be length bytes long starting at base. virtual ~streambuf() Deletes the reserve area if one is allocated. 4-90 iostream Package streambuf class Member Functions int allocate() Tries to set up a reserve area. If a reserve area already exists or is unbuffered, it returns 0 without doing anything. If the attempt to allocate space succeeds, allocate() returns 1; otherwise, it returns EOF. No nonvirtual member functions of streambuf call allocate(). char *base() Returns a pointer to the first byte of the reserve area. The space between base() and ebuf() is the reserve area. int blen() Returns the size, in type char, of the current reserve area. virtual int doallocate() In streambuf, it tries to allocate a reserve area using the new operator. In classes derived from streambuf, this function is called when allocate() determines that space is needed. doallocate() is required to call setb(), to provide a reserve area, or to return EOF if it cannot. It is called only if both unbuffered() and base() are 0. char *eback() Returns a pointer to a lower bound on gptr(). The space between eback() and gptr() is available for putback operations. char *ebuf() Returns a pointer to the byte after the last byte of the reserve area. char *egptr() Returns a pointer to the byte after the last byte of the get area. char *epptr() Returns a pointer to the byte after the last byte of the put area. iostream Package 4-91 streambuf class int fd() Returns the file descriptor associated with the streambuf object, if any; otherwise, it returns -1. void fd(int f) Sets the file descriptor associated with the streambuf object to f. FILE *fp() Returns the file pointer associated with the streambuf object, if any; otherwise, it returns 0. void fp(FILE *f) Sets the file pointer associated with the streambuf object to f. void gbump(int n) Increments gptr() by n, which can be a positive or a negative number. No checks are made on whether the new value of gptr()is in bounds. char *gptr() Returns a pointer to the first byte of the get area. The characters available are those between gptr() and egptr(). The next character fetched will be *gptr() unless egptr() is less than or equal to gptr(). int in_avail() Returns the number of characters immediately available in the get area for fetching. This number is the number of characters that can be fetched with confidence that an error will not be reported. int out_waiting() Returns the number of characters in the put area that have not been consumed (by the ultimate consumer). virtual int overflow(int c) In streambuf, this function should be treated as if its behavior is undefined; classes derived from streambuf should always define it. 4-92 iostream Package streambuf class In classes derived from streambuf, it is called to consume characters. If c is not EOF, overflow(c) also must either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr(), call setp() to establish a new put area, and (if c != EOF) store c using sputc(). overflow(c) should return EOF to indicate an error; otherwise, it should return something else. virtual int pbackfail(int c) In streambuf, this function always returns EOF. In classes derived from streambuf, this function is called when eback() equals gptr() and an attempt has been made to put c back. If this situation can be managed (for example, by repositioning an external file), pbackfail(c) should return c; otherwise, it should return EOF. char *pbase() Returns a pointer to the put area base. Characters between pbase() and pptr() are stored into the buffer but are not yet consumed. void pbump(int n) Increments pptr() by n, which can be positive or negative. No checks are made on whether the new value of pptr() is in bounds. char *pptr() Returns a pointer to the first byte of the put area. The space between pptr() and epptr() is the put area. int sbumpc() Moves the get pointer forward one character and returns the character it moved past. The function returns EOF if the get pointer is currently at the end of the sequence. virtual streampos seekoff(streamoff off, (ios::)seek_dir dir, int mode) In streambuf, this function returns EOF. iostream Package 4-93 streambuf class In classes derived from streambuf, it repositions the abstract get and put pointers (not pptr() and gptr()). mode specifies whether to modify the put pointer (ios::out bit set) or the get pointer (ios::in bit set) or both pointers. off is interpreted as a byte offset (it is a signed value). For the meanings of dir, see the explanation of the enumerated type seek_dir in class ios. A class derived from streambuf is not required to support repositioning. If the derived class does not, then seekoff() should return EOF. If the derived class does support repositioning, seekoff() should return the new position or EOF on error. virtual streampos seekpos(streampos pos, int mode) In streambuf, this function returns seekoff(streamoff(pos), ios::beg, mode). To define seeking in a derived class, you can often define seekoff() and use the inherited streambuf::seekpos. In classes derived from streambuf, this function repositions the streambuf get pointer, put pointer, or both, to pos. mode specifies the affected pointers. seekpos() returns the argument pos or EOF if the class does not support repositioning or if an error occurs. streampos(0) signifies the beginning of the file; streampos(EOF) indicates an error. void setb(char *b, char *eb, int a) Sets base() to b and ebuf() to eb. The a argument controls whether the reserve area will be subject to automatic deletion. If a is nonzero, then b will be deleted when base() is changed by another call to setb(), or when the destructor is called for the streambuf object. If b and eb are both null, then the reserve area effectively does not exist. If b is nonnull, a reserve area exists even if eb is less than b (in which case the reserve area has 0 length). virtual streambuf *setbuf(char *ptr, int len) streambuf *setbuf(unsigned char *ptr, int len) In streambuf, this function honors the request for a reserve area if there is none. 4-94 iostream Package streambuf class In classes derived from streambuf, this function offers for use as a reserve area the array at ptr with len bytes. Normally, if ptr or len is 0, the action is interpreted as a request to make the streambuf object unbuffered. The derived class has the choice of using or not using this area by accepting or ignoring the request. setbuf() should return a reference to the streambuf object if the derived class honors the request; otherwise, it should return 0. streambuf *setbuf(char *ptr, int len, int i) Offers the len bytes starting at ptr as the reserve area. If ptr is null, or len is 0 or negative, then the function requests an unbuffered state. Whether the offered area is used or a request for an unbuffered state is honored depends on details of the derived class. setbuf() normally returns a reference to the streambuf object, but if the derived class does not accept the offer or honor the request, setbuf() returns 0. void setg(char *eb, char *g, char *eg) Sets eback() to eb, gptr() to g, and egptr() to eg. void setp(char *p, char *ep) Sets base() and pptr() to p and epptr() to ep. int sgetc() Returns the character after the get pointer; it does not move the get pointer. It returns EOF if no character is available. int sgetn(char *ptr, int n) Fetches n characters following the get pointer and copies them to the area starting at ptr. If fewer than n characters occur before the end of the sequence, sgetn() fetches the characters that remain. It repositions the get pointer after the fetched characters and returns the number of characters fetched. int snextc() Moves the get pointer forward one character and returns the character after the new position. If the pointer is at the end of the sequence, either before or after moving forward, the function returns EOF. iostream Package 4-95 streambuf class int sputbackc(char c) Moves the get pointer back one character. c must be the current content of the sequence just before the get pointer. The underlying mechanism may back up the get pointer or may rearrange its internal data structures so that c is saved. The effect is undefined if c is not the character before the get pointer. The function returns EOF, by calling pbackfail(), when it fails. The conditions under which it can fail depend on the details of the derived class. int sputc(int c) Stores c after the put pointer and moves the put pointer past the stored character (usually this extends the sequence). The function returns EOF when an error occurs. Conditions that can cause errors depend on the derived class. int sputn(const char *s, int n) Stores after the put pointer the n characters starting at s, and moves the put pointer past them. It returns the number of characters successfully stored. Normally n characters are successfully stored, but fewer characters may be stored when errors occur. void stossc() Moves the get pointer ahead one character. If the pointer started at the end of the sequence, stossc() has no effect. virtual int sync() In streambuf this function returns 0 if the get area is empty and no unconsumed characters are present; otherwise, it returns EOF. In classes derived from streambuf, this function is called to let derived classes examine the state of the put, get, and reserve areas, and to synchronize these areas with any external representation. Normally sync() should consume any characters stored into the put area and, if possible, give back to the source any characters in the get area that have not been fetched. When sync() returns, no unconsumed characters should remain and the get area 4-96 iostream Package streambuf class should be empty. If some kind of failure occurs, sync() should return EOF. int unbuffered() Returns the current buffering state flag, which is independent of the actual allocation of a reserve area. This function's primary purpose is to find out if a reserve area is being allocated automatically by allocate(). void unbuffered(int n) Sets the value of the current buffering state flag. If n equals 0, then the streambuf object is buffered; otherwise it is unbuffered. This function's primary purpose is to control whether a reserve area is allocated automatically by allocate(). virtual int underflow() In streambuf, this function should be treated as if its behavior is undefined; classes derived from streambuf must define it. In classes derived from streambuf, it is called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area. Example iostream Package 4-97 streambuf class static const int bufsize = 1024; char buf[bufsize] ; int p, g ; do { in->sgetc() ; 1 g = in->in_avail() ; 2 if (g > bufsize) g = bufsize ; 3 g = in->sgetn(buf,g) ; p = out->sput(buf,g) ; out->sync() ; 4 if (p!=g) error("output error"); } while (g > 0) Provides a way to pass characters into the in and out arrays as soon as the characters become available (as when someone types them from a terminal) as follows: 1 Ensures at least one character is immediately available in the in array (unless the get pointer is at the end of the sequence). 2 Returns the number of characters immediately available. 3 Checks that chunks in which the characters become available are less than bufsize, and that they fit into the arrays. 4 Sends characters put into the out array to the ultimate consumer. 4-98 iostream Package strstream class ________________________________________________________________ strstream class Specializes the iostream class for storing in and fetching from arrays of bytes. Header File #include Alternative Header #include Declaration class strstream: public iostream { public: strstream(); strstream(char *, int, int); strstreambuf *rdbuf(); char *str(); }; Description This class specializes the iostream class for storing in and fetching from arrays of bytes. It handles all predefined data types, and provides an extensive set of options for performing input and output on these data types. Constructors and Destructors strstream() Constructs an strstream object and dynamically allocates space to hold stored characters. strstream(char *cp, int n, int mode) Constructs an strstream object. It stores characters into the array starting at cp and continuing for n bytes. If ios::ate or ios::app is set in mode, cp is presumed to be iostream Package 4-99 strstream class a null-terminated string and storing begins at the null character; otherwise, storing begins at cp. Seeks are permitted anywhere in the array. Member Functions strstreambuf *rdbuf() Returns a pointer to the strstreambuf object associated with a strstream object. char *str() Returns a pointer to an explicit array, to be used as the associated strstreambuf object, if the strstream object was constructed with such an array; otherwise, it returns a pointer to a dynamically allocated area. Until str() is called, deleting the dynamically allocated area is the responsibility of the strstream object. After str() returns, dynamic allocation becomes the responsibility of the user program. After str() has been called, the effect of storing more characters into the strstream object is undefined. 4-100 iostream Package strstreambuf class ________________________________________________________________ strstreambuf class Specializes the streambuf class for input and output performed on arrays of bytes in memory. Header File #include Alternative Header #include Declaration class strstreambuf: public streambuf { public: strstreambuf(); strstreambuf(char *, int, char *); strstreambuf(int); strstreambuf(unsigned char *, int, unsigned char *); strstreambuf(void *(*a)(long), void (*f)(void *)); void freeze(int n = 1); virtual int overflow(int); virtual streambuf *setbuf(char *, int); char *str(); virtual int underflow(); }; Description Objects of this class let you use an array of bytes (a string of characters) in memory as a streambuf object for stream input/output operations on various kinds of data. Mapping between abstract get and put pointers and char * pointers is direct in the sense that a char * is interpreted as logically pointing immediately ahead of the char it actually points to. Moving the pointers iostream Package 4-101 strstreambuf class corresponds to incrementing and decrementing the char * values. To accommodate the need for strings of arbitrary length, this class supports a dynamic mode. When a strstreambuf object is in dynamic mode, space for the character is allocated as needed. When the sequence is extended too far, it is copied to a new array. If your program expects a buffer to be allocated when none was allocated, then the iostream package allocates a default buffer, with a length specified by BUFSIZ as defined in stdio.h. The package then issues the following warning: Warning; a null pointer to streambuf was passed to ios::init() Constructors and Destructors strstreambuf() Constructs an empty strstreambuf object in dynamic mode. This means that space is automatically allocated to accommodate characters put into the strstreambuf object (using the new and delete operators). Because this may require copying the original characters, programs that have many characters to insert should use setbuf() to inform the strstreambuf object about the needed allocation of space, or to use one of the constructors that follow. strstreambuf(int n) Constructs an empty strstreambuf object in dynamic mode. The initial allocation of space is at least n bytes. strstreambuf(char *ptr, int n, char *pstart) strstreambuf(unsigned char *ptr, int n, unsigned char *pstart) Constructs a strstreambuf object to use the bytes starting at ptr. The strstreambuf object is in static mode; it does not grow dynamically. If n is positive, then the n bytes starting at ptr are used as the strstreambuf object. If n is 0, ptr is presumed to point to the beginning of a null-terminated string and the bytes of that string (not including the terminating null character) constitute the strstreambuf object. If n is negative, then the strstreambuf object is presumed to continue indefinitely. 4-102 iostream Package strstreambuf class The get pointer is initialized to ptr. The put pointer is initialized to pstart. If pstart is not null, then the initial sequence for fetching (the get area) consists of the bytes between ptr and pstart. If pstart is null, then storing operations are treated as errors and the initial get area consists of the entire array. strstreambuf(void *(*a)(long n), void (*f)(void *ptr)) Constructs an empty strstreambuf object in dynamic mode. a is used as the allocator function in dynamic mode. The argument passed to a is a long denoting the number of bytes to be allocated. If the a argument is null, the new operator is used. f is used to free (or delete) get, put, or reserve areas returned by a. The argument to f becomes a pointer to the array allocated by a. If f is null, the delete operator is used. iostream Package 4-103 strstreambuf class Member Functions void freeze(int n) Inhibits (freezes) automatic deletion of the current array if n is nonzero, or permits (unfreezes) automatic deletion if n is 0. Deletion normally occurs when more space is needed, or when the strstreambuf object is being destroyed. Only space obtained through dynamic allocation is free. Storing characters into a strstreambuf that was dynamically allocated and is now frozen causes an error (the effect is undefined). If you want to resume storing characters in such a strstreambuf object you can thaw (unfreeze) it. virtual int overflow(int c) In classes derived from streambuf, it is called to consume characters. If c is not EOF, overflow(c) also must either save c or consume it. Although it can be called at other times, this function is usually called when the put area is full and an attempt is being made to store a new character. The normal action is to consume the characters between pbase() and pptr(), call setp() to establish a new put area, and (if c != EOF) store c using sputc(). overflow(c) should return EOF to indicate an error; otherwise, it should return something else. virtual streambuf *setbuf(char *ptr, int n) Causes the strstreambuf object to remember n (if ptr is 0); this ensures that at least n bytes are allocated during the next dynamic mode allocation. char *str() Returns a pointer to the first character in the current array and freezes the strstreambuf object. If the strstreambuf object was constructed with an explicit array, the function returns a pointer to that array. If the strstreambuf object is in dynamic allocation mode but nothing has been restored yet, the returned pointer is null. 4-104 iostream Package strstreambuf class virtual int underflow() In classes derived from streambuf, it is called to supply characters for fetching; that is, to create a condition in which the get area is not empty. If this function is called when characters are in the get area, it should return the first character. If the get area is empty, it should create a nonempty get area and return the next character (which it should also leave in the get area). If no more characters are available, underflow() should return EOF and leave an empty get area. iostream Package 4-105 5 ________________________________________________________________ Messages Package The Messages package provides a way to retrieve messages stored in a catalog or file that is separate from your program. It consists of a single class, Messages, that retrieves the text of a message. Processing a message file on an OpenVMS system requires a message set number and a message number. A message set number is an OpenVMS message identification code, including a facility code (bits 16 through 27) and a facility-specific bit (bit 15); all other bits should be 0. A message number is an integer from 1 to 8191. To process the message file, use the OpenVMS Message Utility (see the OpenVMS Message Utility Manual for details) and link the resulting object code into one of the following: o Your program o A shareable image that your program is linked against o A shareable image that is then specified with the set message command Messages Package 5-1 Messages class ________________________________________________________________ Messages class Retrieves message text for a message number. Header File #include Alternative Header None. Declaration class Messages { public: Messages(const char *filename_arg, int set_arg = 0, const char *default_file_location_arg = (const char *)(NULL)); ~Messages(); const char *text(int msg_arg, const char *fallback_text_arg, int set_arg = 0); }; Constructors and Destructors Messages(const char *filename_arg, int set_arg, const char *default_file_location_arg) Constructs a Messages object. set_arg specifies the message number to set; a value of 0 specifies that the default set be used. filename_arg and default_file_ location_arg are ignored. ~Messages() Deletes a Messages object. Member Function const char *text(int msg_arg, const char *fallback_text_ arg, int set_arg) Returns the text of the message specified by the msg_arg argument. The fallback_text_arg argument indicates the 5-2 Messages Package Messages class text to return if the message cannot be found. The set_arg argument specifies the message set number; a value of 0 causes the system to use the set number provided to the constructor. Depending on the process defaults, the facility, error severity, and message identification code may be appended to the beginning of the message (for example, %CXXL-W- E_ONEXT, prefixed to Can't delete an object that is on a list.). Example The following is a sample message source file: .TITLE MESSAGES_EXAMPLE_MSG Example messages -- VMS message catalog .IDENT '1.0' .FACILITY EXAMPLE, 1 /PREFIX=EXAMPLE_ .BASE 0 .SEVERITY WARNING ! we just want a 0 in the severity field SET <> ! message set number .SEVERITY ERROR EXAMPLE_ERROR .END Entering the following OpenVMS Message Utility commands set the appropriate options and compile this file: $ set message/nofac/nosev/noid $ message/lis MESSAGES_EXAMPLE_MSG The following program retrieves the sample error message: #include #include const char *message_file_name = (const char *)(NULL); const char *message_file_location = (const char *)(NULL); #pragma __extern_model __save #pragma __extern_model __globalvalue extern int EXAMPLE_SET; #pragma __extern_model __restore int message_set_example = EXAMPLE_SET; Messages Package 5-3 Messages class Messages m_example (message_file_name, message_set_example, message_file_location); int main() { cout << "text of example message 1: " << m_example.text(1, "fallback message 1") << "\n"; cout << "text of example message 2: " << m_example.text(2, "fallback message 2") << "\n"; return 0; } The following compiler command compiles the program: $ cxx/lis MESSAGES_EXAMPLE Entering the following link and run sequence retrieves the text of the error message and displays the second fallback message: $ link MESSAGES_EXAMPLE,MESSAGES_EXAMPLE_MSG $ run/nodeb messages_example text of example message 1: This is an example error message text of example message 2: fallback message 2 5-4 Messages Package 6 ________________________________________________________________ Mutex Package The Mutex package provides a way to synchronize access to user-defined objects. It consists of a single class, Mutex, that manages the creation, locking and unlocking of Mutex objects. Construction of a Mutex object creates a recursive mutex that users can lock and unlock using the appropriate member functions or parameterized manipulators. A recursive mutex is a mutex that can be locked many times by the same thread without causing the thread to enter a deadlock state. To completely unlock this kind of mutex, the thread must unlock the mutex the same number of times that the thread locked the mutex. For more information see the Guide to DECthreads manual. ________________________Note ________________________ User-defined objects are not automatically thread safe. Users must supply synchronization for such objects if they are shared between threads. _____________________________________________________ Mutex Package 6-1 Mutex class ________________________________________________________________ Mutex class Provides a means whereby users can synchronize access to user-defined objects. Header File #include Alternative Header #include Declaration class Mutex { public: Mutex(); ~Mutex(); void lock(); void unlock(); int trylock(); }; Description The synchronization process consists of locking and unlocking Mutex objects associated with user-defined objects. Digital recommends that users create a Mutex object for each user-defined object that needs to be synchronized between threads. Users are then responsible for locking and unlocking the Mutex object to coordinate access to the associated object. To do the locking and unlocking, you can use the lock and unlock member functions (see Example). Alternatively, if a user-defined object is derived from the istream or ostream classes, you can use the lock and unlock parameterized manipulators, where the parameter is the Mutex object (see the Global Declarations section in Chapter 4). 6-2 Mutex Package Mutex class Constructors and Destructors Mutex() Constructs a Mutex object, in effect creating but not locking a recursive mutex. ~Mutex() Deletes a Mutex object. Member Functions void lock() Locks a recursive mutex. If the mutex is locked by another thread, the current thread is blocked until the mutex becomes available. void unlock() Unlocks a recursive mutex. int trylock() Immediately returns to the caller a value of 0 if the mutex is already locked by another thread. Otherwise, this function locks the mutex and returns a value of 1. Example #include #include . . . String string1; Mutex string1_lock; string1_lock.lock(); string1 = "Hello, "; string1 += "how are you?"; cout << string1; string1_lock.unlock(); This example synchronizes a sequence of operations on a String object, using the lock() and unlock() member functions. Mutex Package 6-3 7 ________________________________________________________________ Objection Package The Objection package provides a way to implement simple error handling in DEC C++. You can use this package to catch run-time errors encountered in using classes, and to change or restore actions associated with such errors. Objection Package 7-1 Global Declaration ________________________________________________________________ Global Declaration This typedef is used by, but is not a member of, the Objection class. Header #include Alternative Header #include Declaration typedef int Objection_action(const char*); Type Objection_action Is the type of an action routine that can be called by the function Objection::raise. 7-2 Objection Package Objection class ________________________________________________________________ Objection class Provides the capability to handle and report errors. Header #include Alternative Header #include Declaration class Objection { public: Objection(); Objection(Objection_action *); int raise(const char * = ""); Objection_action *appoint(Objection_action *); Objection_action *appoint(); Objection_action *ignore(); }; Description This class provides ways to handle objections. An objection is a potential error condition that your program can encounter. The user appoints an error-handling function. An Objection object's raise() function invokes the appointed function by passing it a character string that contains an error message. At any point in your program, you can appoint a new error-handling function, reappoint the original function, or specify that an objection be ignored. Objection Package 7-3 Objection class Constructors Objection() Constructs an Objection object with no default action (error handler). Objection(Objection_action *new_action) Constructs an Objection object with a pointer to the default error handler. The handler is a function that takes one parameter of type const char *msg and returns an int. See the raise() member function for more information. Member Functions Objection_action *appoint() Specifies that the handler for the objection is the default error handler (if one exists) and returns the previous action associated with the specified objection. Specifies that the objection not be ignored. Objection_action *appoint(Objection_action *new_ action) Specifies a new handler for the objection and returns the previous action associated with the specified objection. Specifies that the objection not be ignored. Objection_action *ignore() Specifies that the objection be ignored (no error handler is invoked if the objection is raised). This function returns the previous action associated with the specified objection. int raise(const char *msg = "") Raises a specified objection, passing a string (error message) to an error handler (if one exists). If no handler exists, or if the handler returns a 0, the default handler is called. The raise function returns the value returned by the last handler it called. 7-4 Objection Package Objection class If no default handler exists, then the function returns 0. A 0 is also returned if the objection is ignored. Generally, the return of a nonzero value means that the error handling succeeded, and the return of a 0 value means the error handling failed. Objection Package 7-5 Objection class The following example changes the default error handler for the stack(int)::overflow_error objection: #include #include #include vectordeclare(int) stackdeclare(int) vectorimplement(int) stackimplement(int) stack(int) s(10); int error(const char *errmsg) { cerr << "ERROR TRAPPED: " << errmsg << " -- ABORTING\n"; cerr.flush(); abort(); return 0; } void main() { Objection_action *save_action; save_action = stack(int)::overflow_error.appoint(error); for(int i=0; i<100; i++) //push too many things onto stack s.push(i); stack(int)::overflow_error.appoint(save_action); } When this example executes, the following message prints out: ERROR TRAPPED: Stack underflow -- ABORTING %SYSTEM-F-OPCCUS, opcode reserved to customer fault at PC=00010BE5, PSL=03C00000 %TRACE-F-TRACEBACK, symbolic stack dump follows module name routine name line rel PC abs PC 0000012D 00010BE5 0000000E 00009346 OBJECTION_EXAMP error 5984 00000045 00003D29 CXXL_OBJECTION Objection::raise 779 00000026 00008F5A OBJECTION_EXAMP main 5993 0000005B 00003D87 00000072 0002DB5E 7-6 Objection Package Objection class ________________________Note ________________________ The message printed on your system differs somewhat from that shown here. _____________________________________________________ Objection Package 7-7 8 ________________________________________________________________ Stopwatch Package The Stopwatch package provides ways to measure intervals of program execution time. The package consists of a single class, Stopwatch. Typically, you use this class during the performance-tuning phase of program development. Stopwatch Package 8-1 Stopwatch class ________________________________________________________________ Stopwatch class Provides the means to measure intervals of time between specified program events. Header #include Alternative Header #include Declaration class Stopwatch { public: Stopwatch(); void start(); void stop(); void reset(); int status() const; double system() const; double user() const; double real() const; static double resolution(); }; Description Objects of this class measure program execution time and return the result in floating-point seconds. The class includes the start, stop, and reset functions familiar to users of a mechanical stopwatch. You can time the entire program or select certain portions of the program to time; for example, a specified loop or program module. You can create a different Stopwatch object for each independent program activity, and name each according to the activity you intend to measure. 8-2 Stopwatch Package Stopwatch class Constructor Stopwatch() Constructs a Stopwatch object with both time and running status initialized to 0. Member Functions double real() const Returns real time (clock time) in double-precision, floating-point seconds. You can call this function while the stopwatch is running. void reset() Resets the current time measurement to 0 without affecting the value of status(). If status() is initially nonzero, time measurement continues uninterrupted after resetting. double resolution() Returns the (system dependent) resolution of measured time in double-precision, floating-point seconds. void start() Begins measuring program execution time when status() is initially 0 (status() becomes nonzero as a consequence of the call). If status()is initially nonzero, the call has no effect. int status() const Indicates whether the stopwatch is running (returns a value of 1) or not running (returns a value of 0). void stop() Halts measurement of program execution time when status() is initially nonzero (status() becomes 0 as a consequence of the call). If status()is initially 0, the call has no effect. double system() const Returns the system CPU time in double-precision, floating- point seconds. You can call this function while the stopwatch is running. Stopwatch Package 8-3 Stopwatch class double user() const Returns the user CPU time in double-precision, floating- point seconds. You can call this function while the stopwatch is running. System Environment On OpenVMS systems, user time returns the total accumu- lated CPU time, and system time returns 0. Resolution is 1/100 second. Example Stopwatch w ; w.start() ; // . . . // some computation you want to time goes here // . . . w.stop() ; cout << "elapsed time was " << w.user() << "\n"; Displays the number of seconds the computation takes to run. The result is a double-precision value. 8-4 Stopwatch Package 9 ________________________________________________________________ String Package The String package consists of the single class String. This class provides ways to assign, concatenate, and compare character strings. This class also provides methods for substring creation and for vector access to a character string. String Package 9-1 String class ________________________________________________________________ String class Provides the capabilities for manipulating sequences of characters. Header #include Alternative Header None. Declaration class String { friend ostream &operator<<(ostream &, const String &); friend istream &operator>>(istream &, String &); friend int operator==(const String &, const String &); friend int operator==(const String &, const char *); friend int operator==(const char *, const String &); friend int operator!=(const String &, const String &); friend int operator!=(const String &, const char *); friend int operator!=(const char *, const String &); friend int operator<(const String &, const String &); friend int operator<(const String &, const char *); friend int operator<(const char *, const String &); friend int operator>(const String &, const String &); friend int operator>(const String &, const char *); friend int operator>(const char *, const String &); friend int operator<=(const String &, const String &); friend int operator<=(const String &, const char *); friend int operator<=(const char *, const String &); friend int operator>=(const String &, const String &); friend int operator>=(const String &, const char *); friend int operator>=(const char *, const String &); friend String operator+(const String &, const String &); friend String operator+(const String &, const char *); friend String operator+(const char *, const String &); 9-2 String Package String class public: String(); String(const String &); String(const char *); String(const char &); ~String(); String &operator=(const String &); String &operator=(const char *); operator char * () const; operator const char * () const; String &operator+=(const String &); String &operator+=(const char *); String operator()(int, int) const; unsigned int length() const; String upper() const; String lower() const; int match(const String &) const; int index(const String &) const; char operator[](int) const; char &operator[](int); }; Description This class provides the means for manipulating sequences of characters, each of which is of the type char. For some applications, the services provided are like those provided by the traditional C string library (strcpy, strcmp, and so forth), but are more efficient and convenient in the context of C++. Overloaded operators provide ways to assign, concatenate, and compare strings. New operators provide simple notations for substring creation and vector access into the string. All comparisons are lexicographic, with the ordering dependent on the character set in which the string is encoded. An index value of 0 indicates the first character in a string object. String Package 9-3 String class Constructors and Destructors String() Constructs a String object initialized to an empty string. String(const char *s) Constructs a String object and initializes it to the null- terminated sequence of characters. String(const char &c) Constructs a String object with a reference to a char datum to initialize the string. String(const String &x) Constructs a String object with a reference to another String to initialize the first String. ~String() Deletes a String object; no user action is required. Overloaded Operators String operator + (const char *s, const String &x) Concatenates a null-terminated sequence of characters to a String object. String operator + (const String &x, const char *s) Concatenates a String object with a null-terminated sequence of characters. String operator + (const String &x, const String &y) Concatenates a String object with another String object. String &operator = (const char *s) Assigns a String object to a null-terminated sequence of characters. String &operator = (const String &x) Assigns a String object to another String object. int operator < (const char *s, const String &x) Tests if a null-terminated sequence of characters is less than a String object; if so, it returns 1. Otherwise, it returns 0. 9-4 String Package String class int operator < (const String &x, const char *s) Tests if a String object is less than a null-terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator < (const String &x, const String &y) Compares two String objects to determine if the first is less than the second; if so, it returns 1. Otherwise, it returns 0. int operator > (const char *s, const String &x) Tests if a null-terminated sequence of characters is greater than a String object; if so, it returns 1. Otherwise, it returns 0. int operator > (const String &x, const char *s) Tests if a String object is greater than a null-terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator > (const String &x, const String &y) Compares two String objects to determine if the first is greater than the second; if so, it returns 1. Otherwise, it returns 0. String &operator += (const char *st2) Concatenates a null-terminated sequence of characters to a String object. String &operator += (const String &st2) Concatenates a String object to another String object. ostream &operator << (ostream &s, const String &x) Inserts the sequence of characters represented by x into the stream s. istream &operator >> (istream &s, String &x) Extracts characters from s using the istream extraction operator, then stores characters in x, replacing the current contents of x and dynamically allocating x as necessary. String Package 9-5 String class int operator == (const char *s, const String &x) Tests if a null-terminated sequence of characters is equal to a String object; if so, it returns 1. Otherwise, it returns 0. int operator == (const String &x, const char *s) Tests if a String object is equal to a null-terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator == (const String &x, const String &y) Compares two String objects to determine equality. If one is equal to the other, it returns 1; otherwise, it returns 0. int operator != (const char *s, const String &x) Tests if a null-terminated sequence of characters is not equal to a String object; if so, it returns 1. Otherwise, it returns 0. int operator != (const String &x, const char *s) Tests if a String object is not equal to a null-terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator != (const String &x, const String &y) Compares two String objects to determine inequality. If they are not equal, the function returns 1; otherwise, it returns 0. int operator <= (const char *s, const String &x) Tests if a null-terminated sequence of characters is less than or equal to a String object; if so, it returns 1. Otherwise, it returns 0. int operator <= (const String &x, const char *s) Tests if a String object is less than or equal to a null- terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator <= (const String &x, const String &y) Compares two String objects to determine if the first is less than or equal to the second; if so, it returns 1. Otherwise, it returns 0. 9-6 String Package String class int operator >= (const char *s, const String &x) Tests if a null-terminated sequence of characters is equal to or greater than a String object; if so, it returns 1. Otherwise, it returns 0. int operator >= (const String &x, const char *s) Tests if a String object is equal to or greater than a null-terminated sequence of characters; if so, it returns 1. Otherwise, it returns 0. int operator >= (const String &x, const String &y) Compares two String objects to determine if the first is equal to or greater than the second; if so, it returns 1. Otherwise, it returns 0. String operator () (int index, int count) const Creates a new String object defined as a substring of the current String, with index as the starting character and count as the length of the substring. char operator [] (int position) const Returns the character at the requested position within the string. If the position is past the end of the string, it returns 0. If the position is negative, the results are undefined. char &operator [] (int position) Returns a reference to the character at the requested position within the string. This reference is potentially invalid after any subsequent call to a non-const member function for the object. If the position is past the end of the string or if the position is negative, the results are undefined. Other Member Functions int index(const String &x) const Returns the index value of the first position where an element of a String object coincides with the value of x. unsigned int length() const Returns the length (number of characters) in a String object. String Package 9-7 String class String lower() const Returns a new String object constructed from a String except that every character is lowercase regardless of its original case. int match(const String &x) const Compares two strings and returns the first index position at which they differ; it returns -1 if the strings match completely. The String argument can be a character pointer. String upper() const Returns a new String constructed from a String except that every character is uppercase regardless of its original case. Examples 1. String x ("The Times of John Doe"); char *y = "Pink Triangles"; if (x != y) cout << "We have two different strings.\n"; x = y; cout << x; The first line of this example provides a character string to the constructor for initialization. The overloaded operators (!=, <<, and =) accept either two String objects or a String and a null-terminate sequence of characters. The last line prints out the following character string: Pink Triangles 2. String x ("The Times of John Doe"); String a (x(18,3)); // Substring is "Doe" String b (x); // b contains all of x In this example, the creation of object a provides a substring of object x to the constructor for object a. The substring begins at position 18 and has a length of 3 characters. The next line creates the object b and initializes it to contain the same value as x. 9-8 String Package String class 3. String x ("World"); String y; y = "Hello"; y += ", " + x + ".\n"; cout << y; This example shows string concatenation. The last line prints out the following message: Hello, World. String Package 9-9 10 ________________________________________________________________ task Package The task package provides coroutine support. A coroutine, or task, is a subroutine that can suspend execution to allow other tasks to run. Static data is shared among all tasks; automatic and register data is allocated separately for each task. Only one task can execute at a time, even on a multiprocessor system. Programming with tasks can be particularly appropriate for simulations or other applications that can be reasonably represented as sets of concurrent activities. This package includes the object and randint classes, the subclasses derived from these classes, and the histogram class. Figure 10-1 shows the inheritance structure of the task package. Figure 10-1 Inheritance Diagram for the task Package Also note the following: o The sched and task classes are intended for use only as base classes. o The task package makes use of the threads library. task Package 10-1 o The task package is not thread safe. You cannot create tasks simultaneously from different threads. 10-2 task Package Global Declarations ________________________________________________________________ Global Declarations The typedef, enum, and extern declarations are used by one or more classes in the task package but they are not members of any particular class. Header #include Alternative Header #include Declaration typedef int(*PFIO)(int, object*); typedef void(*PFV)(); enum { VERBOSE = 1 << 0, CHAIN = 1 << 1, STACK = 1 << 2, }; enum qmodetype { EMODE, WMODE, ZMODE }; task Package 10-3 Global Declarations enum { E_OLINK = 1, E_ONEXT = 2, E_GETEMPTY = 3, E_PUTOBJ = 4, E_PUTFULL = 5, E_BACKOBJ = 6, E_BACKFULL = 7, E_SETCLOCK = 8, E_CLOCKIDLE = 9, E_RESTERM = 10, E_RESRUN = 11, E_NEGTIME = 12, E_RESOBJ = 13, E_HISTO = 14, E_STACK = 15, E_STORE = 16, E_TASKMODE = 17, E_TASKDEL = 18, E_TASKPRE = 19, E_TIMERDEL = 20, E_SCHTIME = 21, E_SCHOBJ = 22, E_QDEL = 23, E_RESULT = 24, E_WAIT = 25, E_FUNCS = 26, E_FRAMES = 27, E_REGMASK = 28, E_FUDGE_SIZE = 29, E_NO_HNDLR = 30, E_BADSIG = 31, E_LOSTHNDLR = 32, E_TASKNAMEOVERRUN = 33 }; extern int _hwm; 10-4 task Package Global Declarations Types enum Print Function Arguments The verbosity argument to print member functions uses the following values: __________________________________________________________ Value_____Explanation_____________________________________ 0 Requests a brief report CHAIN Requests information about tasks on the object's remember chain, and about other objects on the object's o_next chain STACK Requests information about the run-time stack VERBOSE Requests detailed information on the class __________object__________________________________________ To combine several requests, use the bitwise inclusive operator (|). For example: p->print(VERBOSE|CHAIN); enum qmodetype The following values are used by the qhead and qtail classes for managing queues: __________________________________________________________ Value_____Explanation_____________________________________ EMODE Generates a run-time error if full on enqueue or empty on dequeue WMODE Suspends task execution if full on enqueue or empty on dequeue ZMODE Returns NULL if full on enqueue or empty on __________dequeue_________________________________________ enum Exception Codes Descriptions of the E_ codes are given in the Exception Handling sections of the appropriate classes. task Package 10-5 Global Declarations PFIO Is a pointer to a function returning int, which takes arguments of the types int and object *. PFV Is a pointer to a function returning void, which takes no arguments. Other Data extern int _hwm Can be set to a nonzero value before creation of the first task to keep track of the maximum stack size ("high water mark"). The maximum stack size can be printed by the task::print() function. 10-6 task Package erand class ________________________________________________________________ erand class Objects of the erand class are generators of exponentially distributed random numbers. Header #include Alternative Header #include Declaration class erand: public randint { public: int mean; erand(int m); int draw(); }; Member Data int mean Is the mean of the generated random numbers. Constructor erand(int m) Constructs an erand object with m as the mean for the generated random numbers. Member Function int draw() Returns the next random integer generated by the object. task Package 10-7 erand class See Also randint class 10-8 task Package histogram class ________________________________________________________________ histogram class Objects of the histogram class are generators of histograms. Header #include Alternative Header #include Declaration class histogram { public: int l; int r; int binsize; int nbin; int *h; long sum; long sqsum; histogram(int n_bins = 16, int left = 0, int right = 16); ~histogram(); void add(int sample); void print(); }; Description Objects of this class generate histograms. Each such object has nbin bins, spanning a range from l to r. task Package 10-9 histogram class Exception Handling When a run-time error occurs, the following error code is passed to the object::task_error() function: __________________________________________________________ Value_________Error_Description___________________________ E_HISTO Cannot construct a histogram with less than ______________1_bucket_or_the_left_not_less_than_the_right Member Data int binsize Is the size of the range covered by an individual bin. int *h Is a pointer to a vector of nbin integers. Each element of the vector is the number of samples placed into that bin by the add() function. int l Is the lower (left) end of the range of samples. int nbin Is the total number of bins. int r Is the higher (right) end of the range of samples. long sqsum Is the sum of the squares of the integers added to a bin by the add() function. long sum Is the sum of the integers added to a bin by the add() function. Constructors and Destructors histogram(int n_bins = 16, int left = 0, int right = 16) Constructs a histogram object. The arguments are all optional: n_bins specifies the number of bins, left 10-10 task Package histogram class specifies the initial left end of the range and right specifies the initial right end of the range. At instantiation, the member data are initialized as follows: The count in each bin is set to 0. The value of l is left the value of r is right nbin is set to n_bins The values of sqsum and sum are 0. ~histogram() Deletes a histogram object. Member Functions void add(int sample) Adds one to the bin specified by sample. If sample is outside the range of l to r, the range expands by either decreasing l or increasing r; however, nbin remains constant. Thus, the range covered by one bin doubles if the total histogram doubles. void print() Prints on cout the number of entries for each nonempty bin. task Package 10-11 Interrupt_handler class ________________________________________________________________ Interrupt_handler class Interrupt handlers let tasks wait for external events (system signals), and allow the declaration of handler functions for these events. Header #include Alternative Header #include Declaration class Interrupt_handler: public object { public: Interrupt_handler(int); ~Interrupt_handler(); virtual void print(int verbosity, int internal_use = 0); virtual int pending(); virtual objtype o_type(); private: virtual void interrupt(); }; Description Interrupt handlers allow tasks to wait for signals. You can use classes derived from the Interrupt_handler class to overload the interrupt() function. When the signal is raised, the task package immediately calls the interrupt() function. The task package then schedules its own internal interrupt alerter task for execution. Control returns to the task (if any) that was running when the signal was raised. When control returns to the scheduler, the interrupt alerter runs and schedules for execution those tasks that were waiting for the interrupt handler. 10-12 task Package Interrupt_handler class If the run chain (see the sched class) is empty, the scheduler does not cause the program to exit if there are any interrupt handlers that have been created but not yet destroyed. If an interrupt() function is not needed, you can use the Interrupt_handler class without deriving another class from it. For more information on signals, see the C Run-Time Library Reference Manual. Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value_________Error_Description___________________________ E_NO_HNDLR Cannot handle a signal for which there is no handler E_BADSIG Cannot handle a signal with an invalid signal number E_LOSTHNDLR Cannot delete an Interrupt_handler that is not on the stack of them for the given ______________signal______________________________________ Constructors and Destructors Interrupt_handler(int signal_to_catch) Constructs a new Interrupt_handler object that waits for a specified signal. ~Interrupt_handler() Deletes an Interrupt_handler object. Member Functions virtual void interrupt() Does nothing but lets classes derived from the Interrupt_ handler class overload this function to specify actions. Because it is private, you cannot call it directly. task Package 10-13 Interrupt_handler class virtual objtype o_type() Returns object::INTHANDLER. virtual int pending() Returns 0 on the first call after the signal is raised; otherwise, it returns a nonzero value. virtual void print(int verbosity, int internal_use = 0) Prints information about the interrupt handler. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_ use parameter. System Environment The thread system exception handling uses OpenVMS conditions and does not interact directly with signals. Example extern "C" { #include } #include #include #include class floating_exception: public Interrupt_handler { virtual void interrupt(); public: floating_exception(): Interrupt_handler(SIGFPE) {}; }; void floating_exception::interrupt() { cout << "In floating_exception::interrupt -- Floating exception caught!\n"; cout.flush(); } 10-14 task Package Interrupt_handler class int main() { floating_exception sigfpe_handler; raise(SIGFPE); return EXIT_SUCCESS; } This example prints out the following message: In floating_exception::interrupt -- Floating exception caught! task Package 10-15 object class ________________________________________________________________ object class Base class for other classes in the task package and for user-defined classes of objects to be placed in queues (see the qhead and qtail classes). Header #include Alternative Header #include Declaration class object { public: enum objtype { OBJECT, // class object TIMER, // class timer TASK, // class task QHEAD, // class qhead QTAIL, // class qtail INTHANDLER // class Interrupt_handler }; object *o_next; static PFIO error_fct; object(); ~object(); void alert(); void forget(task *p_task_to_forget); void remember(task *p_task); int task_error(int error_code); virtual objtype o_type(); virtual int pending(); virtual void print(int verbosity, int internal_use = 0); 10-16 task Package object class static int task_error(int error_code, object *object_with_problem); static task *this_task(); }; Description This class is a base class for many other classes within the task package. You also can use it to derive user classes to be placed in the task package's queues and so forth. All objects derived from the object class can declare the virtual function object::pending(), which the scheduler uses to determine if an object is ready or not ready. You can provide each kind of object with its own method of determining its state of readiness. Each pending object contains a list (the remember chain) of the waiting task objects. Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value_________Error_Description___________________________ E_OLINK Cannot delete an object with a remembered task E_ONEXT Cannot delete an object that is on a list E_STORE_______Cannot_allocate_more_memory_________________ Member Data PFIO error_fct Points to a function to be called by the task_error function. For more information, see the task_error function. object *o_next Points to the next object in the queue or run chain. task Package 10-17 object class Constructors and Destructors object() Constructs an object object. ~object() Deletes an object object. Member Functions void alert() Changes the state of all task objects remembered by the object from IDLE to RUNNING, puts the task objects on the scheduler's run chain, and removes the task objects from the remembering object's remember chain. You must call the object::alert function for the object when the state of an object changes from pending to ready. void forget(task *p_task_to_forget) Removes, from the remembering object object's remember chain, all occurrences of the task, denoted by the p_task_ to_forget argument. virtual objtype o_type() Returns object::OBJECT. virtual int pending() Always returns a nonzero value. In classes derived from object, pending() returns the ready status of an object: 0 if an object object is ready and a nonzero value if the object object is pending. Classes derived from the object class must define pending() if waiting is instituted. By default, object::pending returns a nonzero value. virtual void print(int verbosity, int internal_use = 0) Prints an object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. 10-18 task Package object class void remember(task *p_task) Puts a task for a pending object on the remember chain and suspends the task, when that task attempts an operation on the pending object. Remembered task objects are alerted when an object of the object class becomes ready. int task_error(int error_code) Is obsolete. Calling p->task_error(e) is equivalent to calling object::task_error(e,p). static int task_error(int error_code, object *object_with_ problem) Called when a run-time error occurs. The error_code argument represents the error number and the object_with_ problem argument represents a pointer to the object that called task_error(). The object::task_error() function examines the variable error_fct and calls this function if it is not NULL. If the function returns 0, task_error() returns to its caller, which may retry the operation. (An infinite loop may result if no appropriate recovery is made.) If the function returns a nonzero value, task_ error() calls exit(error_code). Otherwise, task_error() gives the error number as an argument to print_error(), which prints an error message on cout and task_error() calls exit(error_code). The object_with_problem argument may be NULL if no particular object can be associated with the error. static task *this_task() Returns a pointer to the task object currently running. task Package 10-19 qhead class ________________________________________________________________ qhead class Abstraction for the head of a list of items arranged in a first-in, first-out singly linked list. Header #include Alternative Header #include Declaration class qhead: public object { public: qhead(qmodetype modetype = WMODE, int size = 10000); ~qhead(); qhead *cut(); object *get(); int putback(object *new_queue_element); int rdcount(); int rdmax(); qmodetype rdmode(); void setmode(qmodetype modetype); void setmax(int size); void splice(qtail *delete_tail); qtail *tail(); int pending(); void print(int verbosity, int internal_use = 0); objtype o_type(); }; 10-20 task Package qhead class Description This class provides facilities for taking objects off a queue. A queue is a data structure with an associated list of objects of the object class, or a class derived from the object class in first-in, first-out order. All access to a queue is through either the attached qhead or attached qtail object. You create a queue by creating either a qhead or a qtail object. The other end of the queue is created automatically. You can then obtain a pointer to the tail with the qhead::tail function. Objects have definitions for when they are ready and pending (not ready). The qhead objects are ready when the queue is not empty and pending when the queue is empty. Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value_________Error_Description___________________________ E_BACKFULL Cannot putback an object into a full queue E_BACKOBJ Cannot putback an object into a queue if the object is on another queue E_GETEMPTY Cannot get an object from an empty queue E_QDEL Cannot delete a queue that has an object in the queue E_STORE_______Cannot_allocate_more_memory_________________ Constructors and Destructors qhead(qmodetype modetype = WMODE, int size = 10000) Constructs a qhead object. The modetype argument determines what happens when an object of the qhead class is pending. The choices are WMODE (wait mode), EMODE (error mode), or ZMODE (0 mode); the default is WMODE (see the get() function for more information). The size argument sets the maximum length of the queue attached to a qhead object; the default is 10,000. task Package 10-21 qhead class The maximum size of the queue does not affect the amount of memory occupied by the queue when the queue is empty. ~qhead() Deletes a qhead object. 10-22 task Package qhead class Member Functions qhead *cut() Splits a queue into two queues. One queue has a new qhead object, which the return value points to, and the original qtail object; it contains the objects from the original queue. The other queue has the original qhead object and a new qtail object; this queue is empty. You can use this function to insert a filter into an existing queue without changing the queue's appearance to functions that access the ends of the queue, and without halting the flow through the queue of objects. object *get() Returns a pointer to the object at the head of the queue when the queue is not empty. The object is removed from the queue. If the queue is empty, behavior depends on the mode of the qhead object. In WMODE, a task that executes qhead::get() on an empty queue suspends until that queue is not empty. In EMODE, executing qhead::get() on an empty queue causes a run-time error. In WMODE, executing qhead::get() on an empty queue returns the NULL pointer instead of a pointer to an object. virtual objtype o_type() Returns object::QHEAD. int pending() Specifies that get operations on a queue must wait until an object is put in the queue. It returns a nonzero value if the queue attached to a qhead object is empty; otherwise, it returns 0. void print (int verbosity, int internal_use = 0) Prints a qhead object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. task Package 10-23 qhead class int putback(object *new_queue_element) Inserts at the head of the queue the object that the new_ queue_element argument points to, and returns a value of 1 on success. This lets the qhead object operate as a stack (hence, the name putback). Space must be available in the queue for it to succeed. Calling qhead::putback() for a full queue causes a run-time error in both EMODE and WMODE and returns NULL in ZMODE. int rdcount() Returns the current number of objects in the queue attached to a qhead object. int rdmax() Returns the maximum length of the queue. qmodetype rdmode() Returns the current mode of a qhead object, which can be EMODE, WMODE, or ZMODE. void setmode(qmodetype modetype) Sets the mode of a qhead object to modetype, which can be EMODE, WMODE, or ZMODE. void setmax(int size) Sets size as the maximum length of the queue attached to a qhead object. You can set size to a number less than the current number of objects of the object class, but that means you cannot put any more objects of the object class on the queue until the length of the queue has been reduced below the limit you set. void splice(qtail *delete_tail) Forms a single queue by appending a queue attached to a qhead object onto the queue referenced in the argument. Typically, this reverses the action of a previous qhead::cut() function. The extra qhead and qtail objects are deleted. Waiting tasks resume execution if merging the two creates a nonempty queue (if the task was trying to get) or an empty queue (if the task was trying to put). 10-24 task Package qhead class qtail *tail() Creates a qtail object for the queue attached to a qhead object (if none exists) and returns a pointer to the new qtail object. task Package 10-25 qtail class ________________________________________________________________ qtail class Abstraction for the tail of a list of items in a first-in, first-out singly linked list. Header #include Alternative Header #include Declaration class qtail: public object { friend class qhead; public: qtail(qmodetype modetype = WMODE, int size = 10000); ~qtail(); qtail *cut(); qhead *head(); int put(object *new_queue_element); int rdspace(); int rdmax(); qmodetype rdmode(); void setmode(qmodetype modetype); void setmax(int size); void splice(qhead *delete_head); int pending(); void print(int verbosity, int internal_use = 0); objtype o_type(); }; 10-26 task Package qtail class Description This class provides facilities for putting objects into a queue. A queue is a data structure with an associated list of objects of the object class, or a class derived from the object class in first-in, first-out order. All access to a queue is through either the attached qhead or qtail object. You create a queue by creating either a qhead or a qtail object. The other end of the queue is created automatically. You can then obtain a pointer to the head with the qtail::head function. Objects have definitions for when they are ready and pending (not ready). The qtail objects are ready when the queue is not full and pending when the queue is full. Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value_________Error_Description___________________________ E_PUTFULL Cannot put an object into a full queue E_PUTOBJ Cannot put an object into queue if the object is on another queue E_QDEL Cannot delete a queue that has an object in the queue E_STORE_______Cannot_allocate_more_memory_________________ Constructors and Destructors qtail(qmodetype modetype = WMODE, int size = 10000) Constructs a qtail object. The modetype argument specifies the mode (set by the constructor) that controls what happens when an object of the qtail class is pending. The choices are WMODE (wait mode), EMODE (error mode), or ZMODE (0 mode); WMODE is the default. (See the put() function for more information.) The size argument specifies the maximum length of the queue attached to a qhead object; the default is 10,000. task Package 10-27 qtail class The maximum size of the queue does not affect the amount of memory occupied by the queue when the queue is empty. ~qtail() Deletes a qtail object. 10-28 task Package qtail class Member Functions qtail *cut() Splits a queue into two queues. One queue has a new qtail object (to which the return value points) and the original qhead object; it contains the objects from the original queue. The other queue has the original qtail object and a new qhead object; this queue is empty. You can use this function to insert a filter into an existing queue, without changing the queue's appearance to functions that access the ends of the queue, and without halting the flow through the queue of objects. qhead *head() Creates a qhead object for the queue attached to a qtail object (if none exists) and returns a pointer to the new qhead object. virtual objtype o_type() Returns object::QTAIL. int pending() Specifies that get operations on a queue must wait until an object is put in the queue. It returns a nonzero value if the queue is empty; otherwise, it returns 0. virtual void print(int verbosity, int internal_use = 0) Prints a qtail object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. int put(object *new_queue_element) Adds the object denoted by the new_queue_element argument to the tail of the queue attached to a qtail object; returns a value of 1 on success. If the queue is full, the behavior depends on the mode of the qtail object. In WMODE, an object of class task that executes qhead::put() on a full queue suspends until that queue is not full. Calling qhead::put() for a full queue causes a run-time error in EMODE and returns NULL in ZMODE. task Package 10-29 qtail class int rdspace() Returns the number of object objects that can be inserted into the queue before it becomes full. int rdmax() Returns the maximum length of the queue. qmodetype rdmode() Returns the current mode of a qtail object, which can be EMODE, WMODE, or ZMODE. void setmode(qmodetype modetype) Sets the mode of a qtail object to modetype, which can be EMODE, WMODE, or ZMODE. void setmax(int size) Sets size as the maximum length of the queue. You can set size to a number less than the current number of objects of the object class, but that means you cannot put any more objects of the object class on the queue until the length of the queue has been reduced below the limit you set. void splice(qhead *delete_head) Forms a single queue by appending a queue attached to a qtail onto the queue referenced in the argument. Typically, this reverses the action of a previous qtail::cut(). The extra qhead and qtail objects are deleted. Waiting tasks resume execution if merging the two queues creates a nonempty queue (if the task was trying to get) or an empty queue (if the task was trying to put). 10-30 task Package randint class ________________________________________________________________ randint class Objects of the randint class generate uniformly dis- tributed random numbers. Header #include Alternative Header #include Declaration class randint { public: randint(long seed=0); int draw(); float fdraw(); void seed(long seed); }; Description Objects of this class generate uniformly distributed random numbers. Each random-number generator object produces a sequence that is independent of other random- number generator objects. Constructor randint(long seed) Constructs an object of the randint class. The seed argument is used as the seed and is optional. Different seeds produce different sequences of generated numbers; not all seeds produce useful sequences. task Package 10-31 randint class Member Functions float fdraw() Returns the next random number generated by the object. The number is a floating-point value in the range 0 to 1. int draw() Returns the next random number generated by the object. The number is an integer value in the range from 0 to RAND_MAX, which is defined in the ANSI C header, stdlib.h. void seed(long seed) Reinitializes the object with the seed seed. Example extern "C" { #include } #include #include main() { randint gen; int i=0; float sum; for (i=0; i<1000; i++) sum += gen.fdraw(); cout<<"Average is " << sum/1000. << "\n"; return EXIT_SUCCESS; } This example prints the average of 1000 floating-point random numbers. 10-32 task Package sched class ________________________________________________________________ sched class Responsible for scheduling and for the functionality common to task and timer objects. Header #include Alternative Header #include Declaration class sched: public object { public: enum statetype { IDLE = 1, RUNNING = 2, TERMINATED = 4 }; protected: sched(); public: static task *clock_task; static PFV exit_fct; void cancel(int result); int dont_wait(); sched *get_priority_sched(); int keep_waiting(); statetype rdstate(); long rdtime(); int result(); int pending(); virtual void print(int verbosity, int internal_use = 0); virtual void setwho(object *alerter); task Package 10-33 sched class static long get_clock(); static sched *get_run_chain(); static int get_exit_status(); static void set_exit_status(int); static void setclock(long); }; #ifdef CXXL_DEFINE_CLOCK #define clock (sched::get_clock()) #endif #define run_chain (sched::get_run_chain()) Description This class provides facilities for checking on the state of a task, manipulating the simulated clock, canceling a task, and checking on the result of a task. You can create instances of classes derived from the sched class, but you cannot create instances of the sched class itself. Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value_________Error_Description___________________________ E_CLOCKIDLE Cannot advance the clock when the clock_task is RUNNING or TERMINATED E_NEGTIME Cannot delay a negative amount of time E_RESOBJ Cannot resume a task or timer if it is already on another queue E_RESRUN Cannot resume a RUNNING task E_RESTERM Cannot resume a TERMINATED task E_SCHOBJ Cannot use class sched other than as a base class E_SCHTIME Cannot execute something at a time that has already passed 10-34 task Package sched class __________________________________________________________ Value_________Error_Description___________________________ E_SETCLOCK Cannot set the clock after it has advanced ______________past_0______________________________________ task Package 10-35 sched class Member Data static task *clock_task Points to the task clock if one exists. static PFV exit_fct Points to the exit function if one exists. Constructor sched() Constructs a sched object initialized to the IDLE state and delay 0. Member Functions void cancel(int result) Puts an object into the TERMINATED state without suspending the caller (that is, without invoking the scheduler); sets the result of the object to result. int dont_wait() Returns the number of calls to keep_waiting(), minus the number of calls to the dont_wait() function, excluding the current call. The return value of this function should equal the number of objects of the object class waiting for external events before the current dont_wait() call. long get_clock() Returns the value of the clock in simulated time units. int get_exit_status() Returns the exit status of the task program. When a task program terminates successfully (without calling task_ error), the program calls exit(i) where i is the value passed by the last caller of sched::set_exit_status(). sched *get_priority_sched() Returns a pointer to a system task's interrupt_alerter if the system gets an awaited signal. If no interrupt occurs, this function returns 0. 10-36 task Package sched class sched *get_run_chain() Returns a pointer to the run chain, the linked list of ready objects belonging to classes derived from the sched class (task and timer objects). int keep_waiting() Keeps the scheduler from exiting when no tasks exist that can be run (an external event could enable an IDLE task to be run). This function should be called when the user program creates an object that waits for an external event. Afterward, when such an object destructs, a call should go to the dont_wait() function. The keep_waiting() function returns the number of calls (not counting the current call) minus the number of calls to the dont_ wait() function. int pending() Returns 0 if the object is in the TERMINATED state; otherwise, it returns a nonzero value. virtual void print(int verbosity, int internal_use = 0) Prints a sched object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. statetype rdstate() Returns the state of the object: RUNNING, IDLE, or TERMINATED. long rdtime() Returns the simulated clock time at which to run the object. int result() Returns the result of a sched object (as set by the task::resultis(), task::cancel(), or sched::cancel() function). If the object is not yet TERMINATED, the calling task suspends and waits for the object to terminate. A task calling result() for itself causes a run-time error. task Package 10-37 sched class void setclock(long new_clock) Initializes the simulated clock to a time specified by the new_clock argument. You can use this function once before the simulated clock has advanced without causing a run-time error. To advance the clock after the initial setting, call the task::delay function. void set_exit_status(int new_exit_status) Sets the exit status of the task program. When a task program terminates successfully (without calling task_ error), the program calls exit(i), where i is the value passed by the last caller of sched::set_exit_status(). virtual void setwho(object *alerter) Records which object alerted the object. The alerter argument should represent a pointer to the object that caused the task package to alert the sched. Macros The DEC C++ Class Library supplies the following macros for compatibility with older C++ class library implementations: clock Calls sched::get_clock(). For this macro to be defined, you must define CXXL_DEFINE_CLOCK on the command line when invoking the compiler, or in your source code before including the task package header. run_chain Calls sched::get_run_chain(). 10-38 task Package task class ________________________________________________________________ task class Serves as the basis for coroutines. Header #include Alternative Header #include Declaration class task: public sched { public: enum modetype { DEDICATED = 1, SHARED = 2 }; protected: task(char *name = (char *)NULL, modetype mode = DEFAULT_MODE, int stacksize = 0); public: task *t_next; char *t_name; ~task(); void cancel(int); void delay(long); long preempt(); void resultis(int); void setwho(object *); void sleep(object *object_waiting_for = (object *)NULL); void wait(object *); int waitlist(object * ...); int waitvec(object **); object *who_alerted_me(); task Package 10-39 task class virtual void print(int verbosity, int internal_use = 0); virtual objtype o_type(); static task *get_task_chain(); }; Description This class is used only as a base class; all coroutine classes are derived from it. All work for an object of a given coroutine type occurs within the constructor for that type. The coroutine class must be exactly one level of derivation from the task class. When the object is created, the constructor takes control and runs until halted by one of the following functions: wait(), waitlist(), waitvec(), sleep(), or resultis(). When a task executes a blocking function on an object that is ready, the operation succeeds immediately and the task continues running; if the object is pending, the task waits. Control then returns to the scheduler, which selects the next task from the ready list or run chain. When a pending object becomes ready, the system puts any task waiting for that object back on the run chain. A task can be in one of the following states: RUNNING Running or ready to run IDLE Waiting for a pending object TERMINATED Completed; not able to resume running (but you can retrieve the result) Exception Handling When a run-time error occurs, the appropriate error code from the following table is passed to the object::task_ error() function: __________________________________________________________ Value____________Error_Description________________________ E_RESULT Cannot call result() on thistask E_STACK Cannot extend stack 10-40 task Package task class __________________________________________________________ Value____________Error_Description________________________ E_STORE Cannot allocate more memory E_TASKDEL Cannot delete a task that is IDLE or RUNNING E_TASKMODE Cannot create a task with a mode other than DEDICATED or SHARED E_TASKNAMEOVERRUNInternal error: data overrun when building default task name E_TASKPRE Cannot preempt a task that is IDLE or TERMINATED E_WAIT___________Cannot_call_wait()_on_thistask___________ Member Data task *t_next Points to the text task on the chain of all task objects; it is equal to NULL if there are no more tasks. char *t_name Points to the null-terminated task name passed to the constructor. If no name was passed to the constructor, then the constructor creates a unique name (and t_name points to it). If the constructor created the name, then the destructor deletes the name. Constructors and Destructors task(char *name = (char *)NULL, modetype mode = DEFAULT_ MODE, int stacksize = 0) Constructs a task object. All three arguments are optional and have default values. If you supply a character pointer, name is used as the task object's name. The argument mode must be DEDICATED or SHARED (or omitted) but only DEDICATED is implemented; thus, the mode argument has no effect. The argument stacksize specifies the minimum size of the task object's stack. By default, the stack size is the same as the default for the underlying thread system. task Package 10-41 task class ________________________Note ________________________ With DEDICATED stacks, the addresses of parameters to a constructor derived from the task class change. This change occurs between the time when the base class (task) constructor is called by the derived class constructor and when the first statement in the derived class constructor begins executing. Constructors for the task class and the classes derived from the task class cannot be inlined. These classes perform actions that start up a child task (in a new thread) and then resume execution of the parent task. On OpenVMS systems, the DEC C++ compiler automatically prevents inlining of constructors for classes derived from task; that is, functions that (implicitly) call task::task (char * = 0, modetype = DEFAULTMODE, int = SIZE). _____________________________________________________ ~task() Deletes an object of the task class. It deletes the task name if the constructor created the name. Member Functions void cancel(int result) Puts a task object into the TERMINATED state without suspending the calling task (that is, without invoking the scheduler); sets the result of the object to result. void delay(long delay) Suspends a task object for the time specified by delay. A delayed task is in the RUNNING state. The task object resumes at the current time on the system clock, plus the time specified by delay. Only calling delay(), or waiting for a timer, advances the clock. task *get_task_chain() Returns a pointer to the first task on the list of all task objects linked by next_t pointers. virtual objtype o_type() Returns object::TASK. 10-42 task Package task class long preempt() Suspends a RUNNING object of the task class making it IDLE. Returns the number of time units left in the task's delay. Calling this function for an IDLE or TERMINATED task causes a run-time error. virtual void print(int verbosity, int internal_use = 0) Prints a task object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. void resultis(int result) Sets the return value of a task object to be the value of result; it puts the task object in the TERMINATED state. To examine the result, call the sched::result() function. The constructor for a class derived from task must not return by any of the following actions: o Executing a return statement o Throwing an exception o Not catching an exception thrown by a subroutine The end of a constructor for a class derived from the task class and the main function must call the resultis() function. A task is pending until its stage changes to TERMINATED. For more information, see sched::pending(). void setwho(object *alerter) Keeps track of which object alerted the object. The alerter argument should represent a pointer to the object that caused the task package to alert the task. void sleep(object *object_waiting_for) Suspends a task object unconditionally (that is, it puts the task object in the IDLE state). The argument object_ waiting_for is optional; if it is pointing to a pending object, the object remembers the task. When the object is no longer pending, the task is rescheduled. If you do not supply an argument, the event that causes the task object to resume remains unspecified. task Package 10-43 task class void wait(object *object_waiting_for) Suspends a task object (it puts the task object in the IDLE state) until that object is ready, if object_ waiting_for points to an object that is pending. If object_waiting_for points to an object that is ready (not pending), then task::wait does not suspend the task object. int waitlist(object *first_object_waiting_for ...) Suspends a task object to wait for one of a list of objects to become ready. The waitlist() function takes a list of object pointers linked by o_next and terminated by a NULL argument. If any of the arguments point to a ready object, then the task object is not suspended. When one of the objects pointed to in the argument list is ready, waitlist() returns the position in the list of the object that caused the return; position numbering starts at 0. int waitvec(object **object_waiting_for_vector) Differs from waitlist() only in that waitvec() takes as an argument the address of a vector holding a list of pointers to objects and terminating NULL. When one of the objects pointed to in the argument vector is ready, waitvec() returns the position in a vector of the object that caused the return; position numbering starts at 0. object *who_alerted_me() Returns a pointer to the object whose state change, from pending to ready, caused a task to be put back on the run chain (put in the RUNNING state). Example long t = sched::get_clock; delay(10000); Delays a task so that it resumes executing at t+10,000. 10-44 task Package timer class ________________________________________________________________ timer class A timer delays for a specified amount of simulated time. Header #include Alternative Header #include Declaration class timer: public sched { public: timer(long delay); ~timer(); void reset(long delay); void setwho(object *alerter); virtual void print(int verbosity, int internal_use = 0); virtual objtype o_type(); }; Description Objects of this class are timers. When a timer is created its state is RUNNING, and it is scheduled to change its state to TERMINATED after a specified number of time units. When the timer becomes TERMINATED, tasks waiting for it are scheduled to resume execution. task Package 10-45 timer class Exception Handling When a run-time error occurs, the following error code is passed to the object::task_error() function: __________________________________________________________ Value_________Error_Description___________________________ E_TIMERDEL Cannot delete a timer that is IDLE or ______________RUNNING_____________________________________ Constructors and Destructors timer(long delay) Constructs an object of the timer class and schedules it for delay time units after the current clock time. ~timer() Deletes an object of the timer class; the timer's state must be TERMINATED. Member Functions virtual objtype o_type() Returns object::TIMER. virtual void print(int verbosity, int internal_use = 0) Prints a timer object on cout. The verbosity argument specifies the information to be printed. For more information, see the enum Print Function Arguments section under Global Declarations for the task package. Do not supply a value for the internal_use parameter. void reset(long delay) Sets the state of the timer to RUNNING (even if it was TERMINATED) and reschedules it to terminate after the specified delay from the current simulated time. void setwho(object *alerter) Returns NULL. 10-46 task Package timer class Example extern "C" { #include } #include #include class DelayTask: public task { public: DelayTask(char *, long); }; // This task just does a delay, much like a timer. DelayTask::DelayTask(char *task_name, long delay_length): task(task_name) { cout << "at beginning of DelayTask, clock is " << sched::get_clock() << "\n"; delay(delay_length); cout << "at end of DelayTask, clock is " << sched::get_clock() << "\n"; thistask->resultis(0); } int main() { cout << "at beginning of main\n"; cout << "creating task\n"; DelayTask delay_task1("delay_task1", 100); cout << "creating timer\n"; timer *pt1 = new timer(10); cout << "waiting for timer\n"; thistask->wait(pt1); cout << "clock is " << sched::get_clock() << "\n"; task Package 10-47 timer class cout << "resetting timer\n"; pt1->reset(1000); cout << "waiting for timer\n"; thistask->wait(pt1); cout << "clock is " << sched::get_clock() << "\n"; cout << "at end of main\n"; thistask->resultis(0); return EXIT_SUCCESS; } This code generates the following output: at beginning of main creating task at beginning of DelayTask, clock is 0 creating timer waiting for timer clock is 10 resetting timer waiting for timer at end of DelayTask, clock is 100 clock is 1010 at end of main 10-48 task Package urand class ________________________________________________________________ urand class Objects of the urand class generate uniformly distributed random integers within a given range from a low to a high value. Header #include Alternative Header #include Declaration class urand: public randint { public: int low; int high; urand(int arg_low, int arg_high); int draw(); }; Data Members int low Is the lower bound of the range of generated random numbers. int high Is the upper bound of the range of generated random numbers. task Package 10-49 urand class Constructor urand(int arg_low, int arg_high) Constructs an object of the urand class. Generated random numbers are uniformly distributed from arg_low to arg_ high. Member Function int draw() Returns the next random integer generated by the object. See Also randint class 10-50 task Package 11 ________________________________________________________________ vector Package The vector package provides ways to define vectors or stacks of objects of any type by using the macro expansion capability of the DEC C++ preprocessor. To declare a generic vector: 1. Include the header in your program and declare the vector class as follows: declare(vector, TYPE) TYPE may be any valid C++ type name. Make sure you define the declare macro in every file that references this new vector data type. 2. Expand the implementation of all function bodies as follows: implement(vector, TYPE) This implement macro must appear once in a program. 3. Declare objects of type vector and TYPE and use the index operator to reference these objects. The following is an example of declaration and referencing: class MyType {/* . . . */}; declare(vector,MyType) implement(vector,MyType) vector(MyType) vec1(100), vec2(5); MyType x,y; // . . . if(vec2[4] == y) vec1[98] = x; vector Package 11-1 The TYPE parameter must be an identifier. If it is not a class name, a fundamental type, or a type name, create a name for the type using a typedef declaration. For example: typedef char *PCHAR; declare(vector, PCHAR) implement(vector, PCHAR) implement(vector, PCHAR) void f() { vector(PCHAR) ptrvec(10); char *p = "Text"; ptrvec[0] = p; // ... } Thread Safety The generation of error messages within the vector package is not thread safe; the package relies on static members to handle the current error message and there is no synchonization between threads. If this creates a problem for your application, Digital recommends that you define a single Mutex object to synchronize all use of the vector package. For more information on synchronizing access to user-defined objects, see Chapter 6. 11-2 vector Package stack(TYPE) class ________________________________________________________________ stack(TYPE) class Provides a generic (parameterized) data abstraction for a fixed-sized stack of objects of some given type. Header #include Alternative Header #include Compile-Time Parameter TYPE-The type of the objects in the stack. It must be an identifier. Declaration class stack(TYPE): private vector(TYPE) { public: stack(TYPE)(int); // objection size_error stack(TYPE)(stack(TYPE) &); void push(TYPE); // objection overflow_error TYPE pop(); // objection underflow_error TYPE &top(); // objection no_top_error int full(); int empty(); int size(); int size_used(); static Objection overflow_error; static Objection underflow_error; static Objection no_top_error; }; vector Package 11-3 stack(TYPE) class Description This class provides a generic (parameterized) data abstraction for a fixed-sized stack of objects of some given type. Before a stack object can be declared or implemented, the base class, a vector object with the same type parameter, must also be declared and implemented. To declare a stack object you need to both declare and implement the base vector class and the stack class. Exception Handling Exceptions are implemented with the Objection package. The initial action function for all objections prints an error message on cerr and calls abort(). Constructors stack(TYPE)(int size) Constructs a stack object with room for size elements in the stack. If size is less than or equal to 0, the objection vector(TYPE)::size_error is raised. stack(TYPE)(stack(TYPE) &src) Constructs a stack object that takes the initial values of the elements from another stack object of the same type and size. Member Data The following objections are raised for the stack errors described. static Objection no_top_error Attempted to reference the top of an empty stack. static Objection overflow_error Attempted to push too many elements onto the stack. static Objection underflow_error Attempted to pop an empty stack. 11-4 vector Package stack(TYPE) class Member Functions int empty() Returns TRUE if the stack is empty; otherwise, it returns FALSE. int full() Returns TRUE if the stack is full; otherwise, it returns FALSE. TYPE pop() Pops an element off the top of the stack. If the stack underflows, the objection stack(TYPE)::underflow_error is raised. void push(TYPE new_elem) Pushes an element onto the stack. If the stack overflows, the objection stack(TYPE)::overflow_error is raised. int size() Returns the maximum number of elements in the stack. int size_used() Returns the number of elements currently used in a generic stack. TYPE &top() Returns a reference to the element on the top of the stack. If the stack is empty, the objection stack(TYPE)::no_ top_error is raised. Example declare(vector, int) implement(vector, int) declare(stack, int) implement(stack, int) vector Package 11-5 stack(TYPE) class void f() { stack(int) st(20); st.push(17); // ... } This example shows the four steps required to declare and implement the base vector class and to declare and implement the stack class. See Also Objection Package (see Chapter 7) generic Package (see Chapter 3) vector(TYPE) class 11-6 vector Package vector(TYPE) class ________________________________________________________________ vector(TYPE) class Provides the (parameterized) data abstraction for a fixed- sized vector of objects of some given type. Header #include Alternative Header #include Compile-Time Parameter TYPE-The type of the objects in the vector. It must be an identifier. Declaration class vector(TYPE) { public: // objection size_error vector(TYPE)(int); vector(TYPE)(vector(TYPE) &); ~vector(TYPE)(); // objection copy_size_error vector(TYPE) &operator=(vector(TYPE) &); TYPE &elem(int); // objection index_error TYPE &operator[](int); int size(); void set_size(int); static Objection size_error; static Objection copy_size_error; static Objection index_error; }; vector Package 11-7 vector(TYPE) class Description This class provides the (parameterized) data abstraction for a fixed-sized vector of objects of some given type. Exception Handling Exceptions are implemented with the Objection package. The initial action function for all objections prints an error message on cerr and calls abort(). Constructors and Destructors vector(TYPE)(int new_size) Constructs a vector object with the integer argument representing the number of elements in the vector. If the number of elements is less than or equal to 0, the objection vector(TYPE)::size_error is raised. vector(TYPE)(vector(TYPE) &src) Constructs a vector object that takes initial values of the elements from another vector object of the same type and size. ~vector(TYPE)() Deletes a vector object. Member Data The following objections are raised for the vector errors described. static Objection copy_size_error Attempted to assign a vector to another vector that has a different number of elements. static Objection index_error Attempted to reference a vector element with a subscript out of range. static Objection size_error Attempted to create a vector with less than one element in it. 11-8 vector Package vector(TYPE) class Overloaded Operators vector(TYPE) &operator = (vector(TYPE) &src) Assigns a vector to another vector. If the sizes of the vectors are different, the objection vector(TYPE)::copy_ size_error is raised. TYPE &operator [] (int i) Returns a reference to the ith element in the vec- tor. The value of i has a range from 0 to size()- 1. If the subscript is out of bounds, the objection vector(TYPE)::index_error is raised. Other Member Functions TYPE &elem(int i) Behaves like operator [] but without bounds checking. void set_size(int new_size) Changes the size of the vector. int size() Returns the number of elements in the vector. See Also Objection Package generic Package vector Package 11-9 ________________________________________________________________ Index A cin stream object, 4-1 ___________________________ Class abs, 2-8 complex, 2-4 to 2-10 add, 10-11 c_exception, 2-11 to 2-13 adjustfield, 4-37 erand, 10-7 to 10-8 alert, 10-18 filebuf, 4-14 to 4-18 allocate, 4-91 fstream, 4-19 to 4-21 appoint, 7-4 histogram, 10-9 to 10-11 arg, 2-8 IAPP(TYPE), 4-22 arg1, 2-8 ifstream, 4-24 to 4-26 attach IMANIP(TYPE), 4-27 to filebuf class, 4-16 4-28 fstream class, 4-20 Interrupt_handler, 10-12 ifstream class, 4-25 to 10-15 ofstream class, 4-65 IOAPP(TYPE), 4-29 IOMANIP(TYPE), 4-31 to B__________________________ 4-32 bad, 4-39 ios, 4-33 to 4-45 base, 4-91 iostream, 4-46 to 4-47 basefield, 4-37 iostream_withassign, 4-48 binsize, 10-10 to 4-49 bitalloc, 4-39 istream, 4-50 to 4-57 blen, 4-91 istream_withassign, 4-58 to 4-59 C__________________________ istrstream, 4-60 to 4-61 callerror macro, 3-4 Messages, 5-2 to 5-4 cancel Mutex, 6-2 to 6-3 sched class, 10-36 OAPP(TYPE), 4-62 task class, 10-42 object, 10-16 to 10-19 cerr stream object, 4-1 Objection, 7-3 to 7-7 ofstream, 4-64 to 4-66 OMANIP(TYPE), 4-67 to 4-68 Index-1 Class (cont'd) Consumer classes, 4-89 ostream, 4-69 to 4-73 copy_size_error, 11-8 ostream_withassign, 4-74 Coroutine, definition of, to 4-75 10-1 ostrstream, 4-76 to 4-77 cos, 2-8 qhead, 10-20 to 10-25 cosh, 2-8 qtail, 10-26 to 10-30 cout stream object, 4-1 randint, 10-31 to 10-32 cut SAPP(TYPE), 4-78 qhead class, 10-23 sched, 10-33 to 10-38 qtail class, 10-29 SMANIP(TYPE), 4-79 to c_exception class, 2-11 to 4-80 2-13 stack(TYPE), 11-3 to 11-6 stdiobuf, 4-81 to 4-83 D__________________________ stdiostream, 4-84 to 4-86 declare2 macro, 3-4 Stopwatch, 8-2 to 8-4 declare macro, 3-4 streambuf, 4-87 to 4-98 dec manipulator, 4-6 String, 9-2 to 9-9 delay, 10-42 strstream, 4-99 to 4-100 Deriving a user class from strstreambuf, 4-101 to ios, 4-3 4-105 doallocate, 4-91 task, 10-39 to 10-44 dont_wait, 10-36 timer, 10-45 to 10-48 draw urand, 10-49 to 10-50 erand class, 10-7 vector(TYPE), 11-7 to randint class, 10-32 11-9 urand class, 10-50 clear, 4-39 clog stream object, 4-1 E__________________________ close eback, 4-91 filebuf class, 4-16 ebuf, 4-91 fstream class, 4-20 egptr, 4-91 ifstream class, 4-25 elem, 11-9 ofstream class, 4-65 empty, 11-5 complex class endl manipulator, 4-6 exception handling, 2-5 ends manipulator, 4-6 complex class, 2-4 to 2-10 enum complex package, 2-1 to Exception codes, 10-5 2-13 print function arguments, global declarations, 2-2 10-5 to 2-3 qmodetype, 10-5 complex_error, 2-12 eof, 4-39 conj, 2-8 epptr, 4-91 Index-2 erand class, 10-7 to 10-8 Generic macros (cont'd) errorhandler macro, 3-4 name2, 3-5 error_fct, 10-17 name3, 3-5 Exception codes, 10-5 name4, 3-5 Exception handling set_handler, 3-5 complex class, 2-5 generic package, 3-1 to exp, 2-8 3-8 Extraction manipulators, global declarations, 3-3 4-6 to 4-13 to 3-8 Extraction operator macros, 3-3 to 3-5 used with cin, 4-2 get istream class, 4-54 F__________________________ qhead class, 10-23 fail, 4-39 get area, 4-88 fd getline, 4-55 filebuf class, 4-16 get_clock, 10-36 streambuf class, 4-92 get_exit_status, 10-36 fdraw, 10-32 get_priority_sched, 10-36 filebuf class, 4-14 to get_run_chain, 10-37 4-18 get_task_chain, 10-42 fill, 4-39 Global declarations flags, 4-40 complex package, 2-2 to floatfield, 4-37 2-3 flush, 4-72 generic package, 3-3 to flush manipulator, 4-6 3-8 forget, 10-18 iostream package, 4-5 to fp, 4-92 4-13 freeze, 4-104 Objection package, 7-2 fstream class, 4-19 to task package, 10-3 to 4-21 10-6 full, 11-5 good, 4-41 Functions gptr, 4-92 pointers to, 10-5 H__________________________ G__________________________ h, 10-10 gbump, 4-92 head, 10-29 gcount, 4-54 hex manipulator, 4-6 Generic macros, 3-3 to 3-5 high, 10-49 callerror, 3-4 histogram class, 10-9 to declare, 3-4 10-11 declare2, 3-4 _hwm, 10-6 errorhandler, 3-4 implement, 3-4 implement2, 3-5 Index-3 io_state, 4-35 I__________________________ ipfx, 4-55 IAPP(TYPE) class, 4-22 isfx, 4-55 Identifiers istream class, 4-50 to beginning with cxxl_ or 4-57 CXXL_, 1-1 istream_withassign class, ifstream class, 4-24 to 4-58 to 4-59 4-26 istrstream class, 4-60 to ignore 4-61 istream class, 4-55 is_open, 4-16 Objection class, 7-4 iword, 4-42 imag, 2-8 IMANIP(TYPE) class, 4-27 K__________________________ to 4-28 keep_waiting, 10-37 implement2 macro, 3-5 implement macro, 3-4 L__________________________ index, 9-7 l, 10-10 index_error, 11-8 length, 9-7 init, 4-41 lock, 6-3 Insertion manipulators, log, 2-8 4-6 to 4-13 low, 10-49 Insertion operator lower, 9-8 used with cout, 4-1 interrupt, 10-13 M Interrupt_handler class, ___________________________ 10-12 to 10-15 Macros in_avail, 4-92 callerror, 3-4 IOAPP(TYPE) class, 4-29 declare, 3-4 IOMANIP(TYPE) class, 4-31 declare2, 3-4 to 4-32 errorhandler, 3-4 IOMANIPdeclare macro, 4-32 generic, 3-3 to 3-5 ios class, 4-33 to 4-45 implement, 3-4 deriving user class from, implement2, 3-5 4-3 name2, 3-5 iostream class, 4-46 to name3, 3-5 4-47 name4, 3-5 iostream package, 4-1 to set_handler, 3-5 4-105 Manipulator macros global declarations, 4-5 IMANIP(TYPE), 4-28 to 4-13 IOMANIP(TYPE), 4-32 iostream_withassign class, OMANIP(TYPE), 4-67 4-48 to 4-49 SMANIP(TYPE), 4-79 Index-4 Manipulators open dec, 4-6 filebuf class, 4-16 endl, 4-6 fstream class, 4-21 ends, 4-6 ifstream class, 4-26 extraction, 4-6 to 4-13 ofstream class, 4-66 flush, 4-6 open_mode, 4-35 hex, 4-6 operator - insertion, 4-6 to 4-13 complex class, 2-6 oct, 4-6 operator != ws, 4-6 complex class, 2-7 match, 9-8 String class, 9-6 mean, 10-7 operator * Messages class, 5-2 to 5-4 complex class, 2-6 Messages package, 5-1 to operator *= 5-4 complex class, 2-7 Mutex class, 6-2 to 6-3 operator + Mutex package, 6-1 to 6-3 complex class, 2-6 String class, 9-4 N__________________________ operator += name2 macro, 3-5 complex class, 2-6 name3 macro, 3-5 String class, 9-5 name4 macro, 3-5 operator / nbin, 10-10 complex class, 2-6 norm, 2-9 operator /= no_top_error, 11-4 complex class, 2-7 operator () O IMANIP(TYPE) class, 4-22 ___________________________ IOMANIP(TYPE) class, 4-29 OAPP(TYPE) class, 4-62 OMANIP(TYPE) class, 4-62 object class, 10-16 to SMANIP(TYPE) class, 4-78 10-19 String class, 9-7 Objection class, 7-3 to operator == 7-7 complex class, 2-7 Objection package, 7-1 to String class, 9-6 7-7 operator [] global declarations, 7-2 vector(TYPE) class, 11-9 Objection_action, 7-2 operator < oct manipulator, 4-6 String class, 9-4 ofstream class, 4-64 to operator << 4-66 complex class, 2-7 OMANIP(TYPE) class, 4-67 IOMANIP(TYPE) class, 4-32 to 4-68 OMANIP(TYPE) class, 4-68 ostream class, 4-71 SMANIP(TYPE) class, 4-80 String class, 9-5 Index-5 operator <= o_type (cont'd) String class, 9-6 qhead class, 10-23 operator = qtail class, 10-29 iostream_withassign class task class, 10-42 , 4-49 timer class, 10-46 istream_withassign class, 4-59 P__________________________ ostream_withassign class, Package, definition of, 4-75 1-1 String class, 9-4 pbackfail, 4-93 vector(TYPE) class, 11-9 pbase, 4-93 operator -= pbump, 4-93 complex class, 2-6 pcount, 4-77 operator > peek, 4-56 String class, 9-5 pending operator >= Interrupt_handler class, String class, 9-7 10-14 operator >> object class, 10-18 complex class, 2-7 qhead class, 10-23 IMANIP(TYPE) class, 4-28 qtail class, 10-29 IOMANIP(TYPE) class, 4-32 sched class, 10-37 istream class, 4-52 PFIO, 10-6 SMANIP(TYPE) class, 4-80 PFV, 10-6 String class, 9-5 Pointers to functions, opfx, 4-72 10-5 osfx, 4-73 polar, 2-9 ostream class, 4-69 to pop, 11-5 4-73 pow, 2-9 ostream_withassign class, pptr, 4-93 4-74 to 4-75 precision, 4-42 ostrstream class, 4-76 to Predefined stream objects 4-77 cerr, 4-1 out_waiting, 4-92 cin, 4-1 overflow clog, 4-1 filebuf class, 4-17 cout, 4-1 stdiobuf class, 4-82 preempt, 10-43 streambuf class, 4-92 print strstreambuf class, 4-104 histogram class, 10-11 overflow_error, 11-4 Interrupt_handler class, o_next, 10-17 10-14 o_type object class, 10-18 Interrupt_handler class, qhead class, 10-23 10-14 qtail class, 10-29 object class, 10-18 sched class, 10-37 Index-6 print (cont'd) rdmode task class, 10-43 qhead class, 10-24 timer class, 10-46 qtail class, 10-30 Print function arguments, rdspace, 10-30 10-5 rdstate Producer classes, 4-89 ios class, 4-42 push, 11-5 sched class, 10-37 put rdtime, 10-37 ostream class, 4-73 read, 4-56 qtail class, 10-29 real put area, 4-88 complex class, 2-9 putback Stopwatch class, 8-3 ostream class, 4-56 remember, 10-19 qhead class, 10-24 reserve area, 4-88 pword, 4-42 reset Stopwatch class, 8-3 Q timer class, 10-46 ___________________________ resetiosflags, 4-10 qhead class, 10-20 to resolution, 8-3 10-25 result, 10-37 qmodetype, 10-5 resultis, 10-43 qtail class, 10-26 to retval, 2-12 10-30 S__________________________ R__________________________ SAPP(TYPE) class, 4-78 r, 10-10 sbumpc, 4-93 raise, 7-4 sched class, 10-33 to randint class, 10-31 to 10-38 10-32 seed, 10-32 rdbuf seekg, 4-56 fstream class, 4-21 seekoff ifstream class, 4-26 filebuf class, 4-17 ios class, 4-42 stdiobuf class, 4-82 istrstreambuf class, 4-61 streambuf class, 4-93 ofstream class, 4-66 seekp, 4-73 ostrstream class, 4-77 seekpos stdiostream class, 4-86 filebuf class, 4-17 strstream class, 4-100 streambuf class, 4-94 rdcount, 10-24 seek_dir, 4-37 rdmax setb, 4-94 qhead class, 10-24 setbuf qtail class, 10-30 filebuf class, 4-17 fstream class, 4-21 ifstream class, 4-26 Index-7 setbuf (cont'd) splice ofstream class, 4-66 qhead class, 10-24 streambuf class, 4-94 qtail class, 10-30 strstreambuf class, 4-104 sputbackc, 4-96 setclock, 10-38 sputc, 4-96 setf, 4-37, 4-43 sputn, 4-96 setfill, 4-10 sqr, 2-9 setg, 4-95 sqrt, 2-9 setiosflags, 4-10, 4-37 sqsum, 10-10 setmax stack(TYPE) class, 11-3 to qhead class, 10-24 11-6 qtail class, 10-30 start, 8-3 setmode status, 8-3 qhead class, 10-24 stdiobuf class, 4-81 to qtail class, 10-30 4-83 setp, 4-95 stdiofile, 4-82 setprecision, 4-11 stdiostream class, 4-84 to setstate, 4-43 4-86 setw, 4-11 stop, 8-3 setwho Stopwatch class, 8-2 to sched class, 10-38 8-4 task class, 10-43 Stopwatch package, 8-1 to timer class, 10-46 8-4 set_complex_error, 2-2 stossc, 4-96 set_exit_status, 10-38 str set_handler macro, 3-5 ostrstream class, 4-77 set_size, 11-9 strstreambuf class, 4-104 sgetc, 4-95 strstream class, 4-100 sgetn, 4-95 streambuf class, 4-87 to sin, 2-9 4-98 sinh, 2-9 Stream objects, predefined sizestack(TYPE) class, cerr, 4-1 11-5 cin, 4-1 sizevector(TYPE) class, clog, 4-1 11-9 cout, 4-1 size_error, 11-8 Stream objects, size_used, 11-5 sychronizing access skipwhite, 4-56 predefined, 4-6 sleep, 10-43 user-defined, 4-11 SMANIP(TYPE) class, 4-79 String class, 9-2 to 9-9 to 4-80 String package, 9-1 to 9-9 snextc, 4-95 Index-8 strstreambuf class, 4-101 to 4-105 U__________________________ strstream class, 4-99 to unbuffered, 4-97 4-100 underflow sum, 10-10 filebuf class, 4-18 sync stdiobuf class, 4-83 filebuf class, 4-18 streambuf class, 4-97 istream class, 4-56 strstreambuf class, 4-105 stdiobuf class, 4-82 underflow_error, 11-4 streambuf class, 4-96 unlock, 6-3 Synchronizing access unsetf, 4-44 to predefined stream upper, 9-8 objects, 4-6 urand class, 10-49 to to user-defined stream 10-50 objects, 4-11 user, 8-4 sync_with_stdio, 4-43 system, 8-3 V__________________________ T Vector ___________________________ how to declare generic, tail, 10-25 11-1 tan, 2-9 vector(TYPE) class, 11-7 tanh, 2-10 to 11-9 Task, definition of, 10-1 vector package, 11-1 to task class, 10-39 to 10-44 11-9 task package, 10-1 to 10-50 W task_error, 10-19 ___________________________ tellg, 4-57 wait, 10-44 tellp, 4-73 waitlist, 10-44 text, 5-2 waitvec, 10-44 this_task, 10-19 who_alerted_me, 10-44 Thread safety, 1-1, 4-3, width, 4-44 11-2 write, 4-73 tie, 4-43 ws manipulator, 4-6 timer class, 10-45 to 10-48 X__________________________ top, 11-5 xalloc, 4-44 trylock, 6-3 Index-9