no copyright!ios_base.3

stream base class

Abstract

The class std::ios_base defines some types and functionality common to all standard stream classes. This class is not templatized and thus only includes stuff which is independent from the character type.

Synopsis

#include <ios>

namespace std
{
  class ios_base
  {
  public:
    class failure;
    class Init;
    typedef void (*event_callback)(event, ios_base&, int);

    enum fmtflags;
    enum iostate;
    enum openmode;
    enum seekdir;
    enum event;

    // values for the formatting flags:
    static fmtflags const boolalpha;
    static fmtflags const dec;
    static fmtflags const fixed;
    static fmtflags const hex;
    static fmtflags const internal;
    static fmtflags const left;
    static fmtflags const oct;
    static fmtflags const right;
    static fmtflags const scientific;
    static fmtflags const showbase;
    static fmtflags const showpoint;
    static fmtflags const showpos;
    static fmtflags const skipws;
    static fmtflags const unitbuf;
    static fmtflags const uppercase;

    static fmtflags const adjustfield;
    static fmtflags const basefield;
    static fmtflags const floatfield;
 
    // values for the state flags:
    static iostate const badbit;
    static iostate const eofbit;
    static iostate const failbit;
    static iostate const goodbit;

    // values for the open modes:
    static openmode const app;
    static openmode const ate;
    static openmode const binary;
    static openmode const in;
    static openmode const out;
    static openmode const trunc;

    // values for the seek directions:
    static seekdir const beg;
    static seekdir const cur;
    static seekdir const end;

  protected:
    ios_base();

  public:
    virtual ~ios_base();

    fmtflags flags() const;
    fmtflags flags(fmtflags f);
    fmtflags setf(fmtflags f);
    fmtflags setf(fmtflags f, fmtflags m);
    fmtflags unsetf(fmtflags m);

    streamsize precision() const;
    streamsize precision(streamsize p);

    streamsize width() const;
    streamsize width(streamsize w);

    locale imbue(locale const& loc);
    locale getloc() const;

    static int xalloc();
    long&  iword(int index);
    void*& pword(int index);

    void register_callback(event_callback cb, int index);
    static bool sync_with_stdio(bool synchronize = true);
  };
}
    

Description

The class ios_base defines a bunch of types and some functionality common to all stream classes. Unlike the other classes involved in I/O, this class is not a template. Correspondingly, it only defines stuff which is independent from the character type. Common stuff depending on the character type is defined in the class basic_ios.html.

The functionality found in ios_base is mainly related to formatting options (with the only exception being sync_with_stdio()): It provides maintainance of formatting flags and parameters and facilities for the user to associate user defined formatting options with stream objects. The class ios_base also maintains a locale object, which is used to provide internationalized numeric formatting and character classification used during formatted reading.

std::ios_base Member Functions

ios_base::ios_base()

Effect
This constructor does not guarantee anything: all members have indeterminate values. The members of the ios_base objects are initialized by the stream object using basic_ios::init().

ios_base::~ios_base()

Effect
All registered callbacks (see register_callback()) are called with the event argument set to erase_event at a time when calling any member of ios_base is still valid (i.e. basically before anything was destrcuted). After this, all resources maintained by the ios_base object (e.g. the the data structure used for pword() and iword()) are released.

ios_base::flags()

Return
This functions returns the current setting of the flags for the object.

ios_base::flags(fmtflags f)

Effect
This function replaces the current format flags with the flags f and returns the flags set prior to this call.
Post Condition
flags() == f
Return
The previous value of flags() is returned.

ios_base::setf(fmtflags f)

Effect
This function sets the flags passed in f and returns the flags set prior to this call. The difference to the flags() member is that after this call both the flags set in f and in the old settings are set. Basically the new value is computed as flags() | f.
Return
The previous value of flags() is returned.
Note
When a flag from a group of format flags (e.g. dec from basefield) should be set, there should be no other flag set from this group. Probably, it is more appropriate to use the other version of setf() which takes two arguments.

ios_base::setf(fmtflag f, fmtflag m)

Effect
This functions frist clears all flags set in m and then sets the flags set in f & m. It then returns the flags set prior to this call. Basically, the new value is computed as (flags() & ~m) | (f & m). A typical use of this function is setting of a flag from a group of format flags (e.g. dec from basefield).
Return
The previous value of flags() is returned.

ios_base::unsetf(fmtflags m)

Effect
This function clears all flags set in m. Basically, the new value is computed as flags() & ~m.

ios_base::precision()

Return
This functions returns the number of digits after the decimal point (i.e. the precision) to be generated by when writing floating point values.

ios_base::precision(streamsize p)

Effect
Changes the number of digits after the decimal point (i.e. the precision) to be generated when writing floating point values to p and returns the value of precision() which was in effect prior to this call.
Return
The previous value of precision() is returned.

ios_base::width()

Return
This functions returns the minimum of characters to be generated (the field width) when writing numeric values (and some others; it will be mentioned in the description of the corresponding functions, if the width is used). If necessary, fill characters are inserted at the position determined by the adjustment flags.

ios_base::width(streamsize w)

Effect
This function changes the field width for the next formatted write of a numeric value to w and then returns the field width which was set prior to this call.
Return
The previous value of width() is returned.
Note
Conventionally, the field width is restored to 0 after it is used by a formatted output function.

ios_base::getloc()

Return
This function returns the current locale object installed in the ios_base object.

ios_base::imbue(locale const& loc)

Effect
First installs the new locale object in the ios_base object and then calls all registered callbacks with the event argument set to imbue_event. Finally, the locale installed prior to this call is returned.
Return
The previous value of getloc() is returned.

ios_base::sync_with_stdio(bool sync = true)

Effect
Calling this function with the argument false allows the standard C++ streams to operate independently from the standard C streams, while the argument true forces the standard C++ streams to be synchronized with the standard C streams. The rationale of this function is mainly a performance concern: If the streams have to be synchronized this might involve serious performance problems for some implementations. This is because an implementation might be forced to implement the standard C++ streams on top of the standard C streams, without the possibility to use buffers because there is basically no way to tell when a user switches between the use of the C and the C++ streams, to guarantee sychronization.

There is actually only a problem if there is heavy use of the standard C++ streams. In this case it is likely that the standard C streams are not used and in these situations sync_with_stdio(false) should be called. Changing the guarantees on synchronization probably has no effect if only the standard C streams are used. On the other hand, if you are mixing use of the standard C++ and the standard C stream, it likely that you want synchronization: For example, it should be avoided that some partial input is stored in a buffer of cin while another portion is stored in a buffer of stdin. For output it is probably also desirable to have synchronization although liberal use of ios_base::skipws and fflush() should solve the problem here.

Return
The function returns the previous argument if there was a previous call. Otherwise it returns true which means that initially the streams are synchronized.
Note
The effect of calling this function after there was some input or output using one of the standard streams is implementation defined! Thus, you should call this function prior to any output to the standard streams. For this implementation, you can call the function at any time since nothing is changed internally, except the value to be returned by the next call that is, the standard C++ streams are always synchronized with the standard C streams. Currently, this is because the standard C++ streams are implemented in terms of the standard C streams.

ios_base::xalloc()

Effect
This function reserves a new entry to associate data with an ios_base object and returns an index which can be used to access this entry using the member functions ios_base::iword() and ios_base::pword(). The reserved entry is reserved for all ios_base objects such that the returned index can be used for all stream. Reserving an entry can mean to just return a count of how many entries are already reserved.

This feature can e.g. be used to implement manipulators which have to store some data like formatting parameters. A typical approach is to have static variable holding the index and have it allocate exactly one entry which is then used by the manipulator and the functions depending on the data set by the manipulator .

ios_base::iword(int index)

Effect
The function iword() accesses data associated with the ios_base object unsing the index index. The reference returned by this objects is only valid until the next call to iword() with a different index, a call to basic_ios::copyfmt(), or the destruction of the ios_base object. According to the standard, on failure this function is supposed to "set the badbit" which sounds reasonable but is unfortunately meaningless because the functions to maintain a stream's state are defined in the derived class basic_ios. However, the function always returns a valid reference, even if the function failed for some reason (unless, of course, setting badbit results in an exception being thrown).

To make it possible to tell whether an entry accessed with iword() was already initialized, new entries are set to zero. Correspondingly, if it is necessary to tell whether the entry was already initialized you should make sure that you are not using the value zero for something sensible. To maintain external data or to ascertain consistency between certain settings, it may be necessary to track certain modifications to the stream object. This can be done be registering a callback function to handle these situations.

Precondition
The argument index was allocated using ios_base::xalloc().
Return
This function returns a reference to a long accessing the data entry specified by the argument. If the entry was accessed the first time, it is initialized to zero.
Note
The reference returned becomes invalid by a call to basic_ios::copyfmt(), another call to iword() with a different index, and destroying the corresponding ios_base object.

ios_base::pword(int index)

Effect
The function pword() accesses data associated with the ios_base object unsing the index index. The reference returned by this objects is only valid until the next call to pword() with a different index, a call to basic_ios::copyfmt(), or the destruction of the ios_base object. According to the standard, on failure this function is supposed to "set the badbit" which sounds reasonable but is unfortunately meaningless because the functions to maintain a stream's state are defined in the derived class basic_ios. However, the function always returns a valid reference, even if the function failed for some reason (unless, of course, setting badbit results in an exception being thrown).

To make it possible to tell whether an entry accessed with pword() was already initialized, new entries are set to zero. Correspondingly, if it is necessary to tell whether the entry was already initialized you should make sure that you are not using the value zero for something sensible. When storing pointers to objects which have to be released you can registering a callback function which is called when certain modifications are applied to a stream.

Precondition
The argument index was allocated using ios_base::xalloc().
Return
This function returns a reference to a void* accessing the data entry specified by the argument. If the entry was accessed the first time, it is initialized to zero.
Note
The reference returned becomes invalid by a call to basic_ios::copyfmt(), another call to pword() with a different index, and destroying the corresponding ios_base object.

ios_base::register_callback( ios_base::event_callback cb, int index)

Effect
register_callback() function registers the function cb as a callback function to be called if certain events occure. The argument index is passed as argument when the function cb is called and can be used to specify parameters to the callback function. The idea is that the actual data is stored using pword() and/or iword().

The callback functions are called in the reverse order of their registration. Thus, a callback registered during the excutation of another callback will not be called until the next event occures. Also, callbacks entered multiple times even with identical arguments will be called multiple times, that is they are not merged.

Requirement
The callback functions shall not throw any exception.

class std::ios_base::failure

namespace std {
  class ios_base::failure: public exception {
  public:
    explicit failure(string const& description);
    virtual ~failure();
    virtual char const* what() const throw;
  };
}
    

The class failure is used as the class thrown if an error is detected by the stream classes. This requires, however, that throwing exceptions is permitted by setting the appropriate flags (see basic_ios::exceptions() for information on how to set these flags) since otherwise only the corresponding state flags is set. This class may also be used as a base class for exceptions thrown by user functions which is especially reasonable for functions called as the result of calling another stream function like e.g. the member functions of a user defined stream buffer.

ios_base::failure::failure(string const& description)

Effect
The constructor of the class ios_base::failure gets a string describing the cause of the error as argument. A copy of description is returned by the default implementation of the what() method.
Post Condition
description == what()

ios_base::failure::~failure()

Effect
The destructor of this class arranges for proper release of the string. It is declared as virtual, making it possible to release classes derived from this class using a pointer to an object of type ios_base::failure (actually, the destructor of the base class exception is already declared as virtual).
Note
Accessing the string returned from the what() member function after the destructor of the corresponding object was executed results in undefined behavior.

ios_base::failure::what()

Effect
The function what() returns a copy of the string passed as constructor argument (using the c_str() method of basic_string). This method is overrides the corresponding method in exception.

std::ios_base::fmtflags

The type fmtflags is used to specific formatting options for formatted I/O with the stream classes. It is also used to specific formatting options when using several facets std::locale::facets, partially because these classes are used by the stream classes to do the actual formatting (see std::num_get and std::num_put).

According to the C++ standard, this type is a bit mask type which basically says that you can use the bit operations on this type. However, it is up to the implementation what type is really used and implementations differ in their approach what to use: Often, this type is a typedef for an integral built-in type (normally for unsigned long) but this is not at all required. This implementation uses an enumeration type. To be useful, the standard defines a set of static constant members in the class ios_base which provide the possible names for the values to be used for this type (thus, the actual values defined by the enumeration are not documented since they would be specific for this implementation anyway: you should use the constants defined in ios_base instead). Although these names normally can be used as constant integral expression (which can thus be used e.g. in the case labels of a switch statement), this is not required by the standard. Also, combinations of flags produced by the bit operations on the type fmtflags cannot be used portably as constant integral expressions (in particular, this fails with this implementation).

Here is an overview of the fmtflag values and what they are used for (this only applies to formatted input or output):

Value Group Effect(s) if this value is set Default
boolalpha none Reading and writing of boolean values uses a textual representation. false
dec basefield Reading and writing of integer values uses decimal base. true
fixed floatfield Writing of floating point values uses fixed-point notation (see precision() for details on how to specify the precision to be used). false
hex basefield Reading and writing of integer values uses hexadecimal base. false
internal adjustfield Fill characters are inserted at a designated internal point in certain generated output (it is identical to specifying right if if there is no such point). For example, for integer output fill characters are inserted after the sign (if there is a sign generated). false
left adjustfield Fill characters are inserted to the right of the generated output (i.e. the output is left adjusted). false
oct basefield Reading and writing of integer values uses octal base. false
right adjustfield Fill characters are inserted to the left of the generated output (i.e. the output is right adjusted). false
scientific floatfield Writing of floating point values uses scientific notation (i.e. the value is written using a mantissa and exponent) false
showbase none A prefix indicating the used base is generated when writing integer values using an octal base (prefix: '0') or a hexadecimal base (prefix: '0x' or 'OX' depending on the setting of uppercase). false
showpoint none A decimal point is always inserted when writing floating point values, even in situations where it would normally be ommitted (e.g. if the point is not followed by a digit). false
showpos none A + sign is generated when writing positive numeric values. false
skipws none When reading formatted input, leading whitespace is skipped. true
unitbuf none The buffer is flushed after each output operation. false
uppercase none Letters generated during numeric output (e.g. when writing integers using a hexadecimal base or the 'e' in scientific notation) are uppercase. false

The last column lists the default setting in newly created streams (more precisely, the setting procuded by the function basic_ios::init()). In addition to these flags, there are three values which define groups of flags:

Value Semantic ... and if none of the flags is set?
adjustfield Flags describing how generated output is adjusted. Fill characters are inserted to the right (i.e. as if left is set).
basefield Flags describing the base to be used when reading or writing integer values. For output a decimal base is used, for input the base depends on the prefix ('0': octal, 'Ox' or '0X': hexadecimal, decimal otherwise).
floatfield Flags describing the formatting when writing floating point values. The more accurate representation of fixed and scientific with the minimum characters is choosen.

If you want to set one of the flags which is member of a group of flags, you have to make sure that you clear any other flags in the same group. Otherwise you will experience some unexpected behavior. To set such a flag, you can either use a manipulator or the ios_base::setf() member function which takes a flag and a mask as argument.

std::ios_base::iostate

The type iostate is used to represent state indications for a stream like a failure indication or that an input stream reached end of file. Like for ios_base::fmftflags, the exact type used for iostate is not defined by the standard. It is only defined that this type is a bitmask type. The values useable for this this type are defined as static constants in ios_base:

Value Semantic
badbit A fatal problem occured, like an exception was thrown during an I/O operation or there is no stream buffer installed.
eofbit An input operation tried to read a character beyond the end of file. Note, that this flag is not set if the input operation finished after reading the last character in a file but before an attempting to read beyond this character (a typical situation is reading lines of files where the last character in the file is a newline character).
failbit An input operation failed to read the requested input, e.g. because an unexpected character was found or because end of file was reached.
goodbit Everything is just fine! This 'bit' is actually defined to be zero (i.e. a value with no bit set), representing the absence of any of the other three bits.

The standard I/O operations always fail if a different bit than goodbit is set. To continue processing after one of the bits was set (e.g. to ignore an offending character and continue processing), you can use the method basic_ios::clear().

std::ios_base::openmode

The type openmode is used as argument for methods opening a file (e.g. std::basic_filebuf::open()) and to specify which position is to be moved in seek operations (e.g. std::basic_streambuf::pubseekoff()). Like for ios_base::fmftflags, the exact type used for openmode is not defined by the standard. It is only defined that this type is a bitmask type. The values useable for this this type are defined as static constants in the class ios_base:

Value Semantic
app When opening a file with this flag set, all characters written to this file are appended at the end of the file: Prior to each write, a seek to the end of the file is made
ate After opening the file, the read and write positions are seeked to the end of the file ('ate' is pronounced like: 'at end'). The difference to app is that this seek happens only once, immediately after opening the file.
binary If this flag is set when opening a file, some character conversions are suppressed for this file. It does not mean, that input and output is done in some binary format! On the other hand, you certainly want to set this flag if you are doing binary I/O to suppress unwanted conversion which are useful only for textual I/O.
in This flag is set when opening a file for input or when modifying the read position of stream buffer.
out This flag is set when opening a file for output or when modifying the write position of stream buffer.
trunc Opening a file with this flag set will remove contents of the opened file (if there were any).

Except for the values ios_base::in and ios_base::out the semantic is specific to the file stream classes ( std::basic_filebuf, std::basic_ifstream, std::basic_ofstream, and std::basic_fstream).

std::ios_base::seekdir

The type seekdir is used to describe the position from which the result of relative seek operations (see basic_streambuf::pubseekoff()) is to be computed. Like for ios_base::fmftflags, the exact type used for seekdir is not defined by the standard. It is only defined that this type is an enumerated. The values useable for this this type are defined as static constants in the class ios_base:

Value Semantic
beg The seek is made from the beginning of the stream. In this case, the relative offset may not be negative.
cur The seek is made from the current position. Whether read or write position is meant depends on the argument describing which position is to be change. Normally, if both the read and write position is to be changed, the seek operation fails if the offset is non-zero and cur is specified.
end The seek is made from the end of the stream. In this case, normally the relative offset may not be positive.

std::ios_base::event

namespace std {
  enum ios_base::event {
    erase_event,
    imbue_event,
    copyfmt_event
  };
}
    
The enumeration event is used to describe the reason why a callback function registered with ios_base::register_callback was called. Here is a list of the possible values and their meaning:

Value Reason
erase_event This event is used when allocated resources should be released. It is called in two situations: The Obvious situation is when the ios_base object is destructed, the other is when basic_ios::copyfmt() is called. When basic_ios::copyfmt() is called, the format flags of the object to which new values are assigned have to be released before the new values can be assigned.
imbue_event This event is used when imbue() is called after the new locale was installed and can be used to mark cached information from the locale as invalid or to update them.
copyfmt_event This event is used when basic_ios::copyfmt() has copied all formatting information. basic_ios::copyfmt() has made only a bitwise copy but this can be insufficient, e.g. when objects are allocated with new to maintain the formatting information. This event can then be used to really copy the objects or to maintain a reference count.

It is not possible to register callbacks for a specific event. Instead, all registered callbacks are called if any of the events occures. Thus, the callback functions should be prepared to handle all of these events.

std::ios_base::event_callback

namespace std {
  class ios_base {
  public:
    typedef void (*event_callback)(event ev, ios_base& ib, int index);
    // ...
  };
}
    
The type event_callback defines the type of the functions used as callback functions which can be registered for an ios_base object. The argument ev defines the reason why the callback was called, the argument ib is a reference to the object for which the callback was registered, and the argument index is the value passed to register_callback() as second argument. The index argument can be used to specify an additional parameter. Its intend is to be used as an argument to pword() and/or iword() to identify the data entry which is to be maintained by the callback function.

Note that you cannot use non-static member functions as callback functions: You can only use functions at namespace scope or static member functions as callback functions, if they have a matching signature. If you need to call a non-static member function, you can create a static member function used as callback which then uses argument index to identify the object for which the member function should be called and then calls this member function:
  class foo {
  public:
    static void callback(std::ios_base::event ev,
                         std::ios_base& ib,
                         int index) {
      foo* fp = dynamic_cast<foo*>(ib.pword(index));
      fp->member(ev, ib);
    } 
    void member(std::ios_base::event ev, std::ios_base& ib);
  };
    

class std::ios_base::Init

namespace std {
  class ios_base::Init {
  public:
    Init();
    ~Init();
  };
}
    
The class Init is used to guarantee that the standard stream objects are constructed prior to an object with static linkage using one of these objects: It is guaranteed that all standard stream objects are constructed prior or during the construction of the first Init object. Although implementations of the C++ standard library are encouraged to construct the standard stream objects early and without user intervention, this is not guaranteed. To play safe, you should define an Init object in each translation prior to the first object with static linkage (i.e. static class members, global objects, objects at namespace scope declared as static, and object at namespace scope declared in unnamed namespaces) whose constructor, or any function called by this function, might write to one of the standard stream objects. However, I guess that all implementations will either construct this the standard stream objects automatically early enough, either by defining an Init object with static linkage in the header <iostream> or by some other technique. For example, for this library it is planned to put the standard stream objects into a shared library and to arrange for proper initialization using initialization features of shared libraries: the first time they are accessed, the shared library has to be loaded, calling the corresponding initialization routines. The constructor of Init would then simply accesses the standard stream objects to make sure the shared library is loaded. However, using the GNU linker this is actually not necessary because this linker orders the constructor in opposite order of the objects being specified on the command line: Since the library file for the C++ standard library is the last argument constructors of global objects defined in this library are processed first.

std::ios_base::Init::Init()

Effect
If the standard stream objects are not yet constructed, this constructor will construct these objects. Objects of type Init can be used to make sure the standard stream objects are constructed prior to accessing them from constructors of objects with static linkage.
Post Condition
All standard stream objects are constructed.

std::ios_base::Init::~Init()

Effect
This destructor does nothing except for the last Init object being destructed: If the last Init object is destructed, all standard output streams are flushed.
Post Condition
If the last Init object was destroyed, all standard stream objects are in sync with their external representation.

See Also

iostream-intro(3), iostream-manipulator(3), basic_filebuf(3), basic_ios(3), basic_streambuf(3) locale(3), num_get(3), num_put(3)
Copyright © 1999 Dietmar Kühl, Claas Solutions (dietmar.kuehl@claas-solutions.de)