Input/output (C++)

Last updated

In the C++ programming language, input/output library refers to a family of class templates and supporting functions in the C++ Standard Library that implement stream-based input/output capabilities. [1] [2] It is an object-oriented alternative to C's FILE-based streams from the C standard library. [3] [4]

Contents

History

Bjarne Stroustrup, the creator of C++, wrote the first version of the stream I/O library in 1984, as a type-safe and extensible alternative to C's I/O library. [5] The library has undergone a number of enhancements since this early version, including the introduction of manipulators to control formatting, and templatization to allow its use with character types other than char.

Standardization in 1998 saw the library moved into the std namespace, and the main header changed from <iostream.h> to <iostream>. It is this standardized version that is covered in the rest of the article.

In the C++23 revision, the header <print> was added, which adds std::print() and std::println(), allowing for formatted printing to any output or file stream.

Overview

Most of the classes in the library are actually very generalized class templates. Each template can operate on various character types, and even the operations themselves, such as how two characters are compared for equality, can be customized. However, the majority of code needs to do input and output operations using only one or two character types, thus most of the time the functionality is accessed through several typedefs, which specify names for commonly used combinations of template and character type.

For example, basic_fstream<CharT,Traits> refers to the generic class template that implements input/output operations on file streams. It is usually used as fstream which is an alias for basic_fstream<char,char_traits<char>>, or, in other words, basic_fstream working on characters of type char with the default character operation set.

The classes in the library could be divided into roughly two categories: abstractions and implementations. Classes, that fall into abstractions category, provide an interface which is sufficient for working with any type of a stream. The code using such classes doesn't depend on the exact location the data is read from or is written to. For example, such code could write data to a file, a memory buffer or a web socket without a recompilation. The implementation classes inherit the abstraction classes and provide an implementation for concrete type of data source or sink. The library provides implementations only for file-based streams and memory buffer-based streams.

The classes in the library could also be divided into two groups by whether it implements low-level or high-level operations. The classes that deal with low-level stuff are called stream buffers. They operate on characters without providing any formatting functionality. These classes are very rarely used directly. The high-level classes are called streams and provide various formatting capabilities. They are built on top of stream buffers.

The following table lists and categorizes all classes provided by the input-output library.

ClassExplanationTypedefs
Stream buffers (low level functionality)
basic_streambufprovides abstract low level input/output interface, that can be implemented for concrete data sources or sinks. Rarely used directly.
  • streambuf – operates on characters of type char
  • wstreambuf – operates on characters of type wchar_t
basic_filebufimplements low level input/output interface for file-based streams. Rarely used directly.
  • filebuf – operates on characters of type char
  • wfilebuf – operates on characters of type wchar_t
basic_stringbufimplements low level input/output interface for string-based streams. Rarely used directly.
  • stringbuf – operates on characters of type char
  • wstringbuf – operates on characters of type wchar_t
Support classes
ios_basemanages formatting information and exception state
basic_iosmanages a stream buffer
  • ios – operates on characters of type char
  • wios – operates on characters of type wchar_t
Input streams buffers (high level functionality)
basic_istreamwraps an abstract stream buffer and provides high level input interface, such as formatting capabilities.
  • istream – operates on characters of type char
  • wistream – operates on characters of type wchar_t
basic_ifstreaman input stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic input stream
  • ifstream – operates on characters of type char
  • wifstream – operates on characters of type wchar_t
basic_istringstreaman input stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic input stream
  • istringstream – operates on characters of type char
  • wistringstream – operates on characters of type wchar_t
Output streams buffers (high level functionality)
basic_ostreamwraps an abstract stream buffer and provides high level output interface, such as formatting capabilities.
  • ostream – operates on characters of type char
  • wostream – operates on characters of type wchar_t
basic_ofstreaman output stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic output stream
  • ofstream – operates on characters of type char
  • wofstream – operates on characters of type wchar_t
basic_ostringstreaman output stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic output stream
  • ostringstream – operates on characters of type char
  • wostringstream – operates on characters of type wchar_t
Input/output streams buffers (high level functionality)
basic_iostreamwraps an abstract stream buffer and provides high level input/output interface, such as formatting capabilities.
  • iostream – operates on characters of type char
  • wiostream – operates on characters of type wchar_t
basic_fstreaman input/output stream that wraps a file stream buffer. Provides functions to open or close a file in addition to those of generic input/output stream
  • fstream – operates on characters of type char
  • wfstream – operates on characters of type wchar_t
basic_stringstreaman input/output stream that wraps a string stream buffer. Provides functions to access the underlying string in addition to those of generic input/output stream
  • stringstream – operates on characters of type char
  • wstringstream – operates on characters of type wchar_t

Header files

The classes of the input/output library reside in several headers.

Stream buffers

There are twelve stream buffer classes defined in the C++ language as the table.

Support classes

ios_base and basic_ios are two classes that manage the lower-level bits of a stream. ios_base stores formatting information and the state of the stream. basic_ios manages the associated stream-buffer. basic_ios is commonly known as simply ios or wios, which are two typedefs for basic_ios with a specific character type. basic_ios and ios_base are very rarely used directly by programmers. Usually, their functionality is accessed through other classes such as iostream which inherit them. [6] [7]

Typedefs

Namedescription
iosconvenience typedef for a basic_ios working with characters of type char
wiosconvenience typedef for a basic_ios working with characters of type wchar_t
streamoffsupports internal operations.
streamposholds the current position of the buffer pointer or file pointer.
wstreamposholds the current position of the buffer pointer or file pointer.
streamsizespecifies the size of the stream.

Formatting manipulators

NameDescription
boolalpha / noboolalphaspecifies whether variables of type bool appear as true and false or as 0 and 1 in the stream.
skipws / noskipwsspecifies whether the white space is skipped in input operations
showbase / noshowbasespecifies whether the notational base of the number is displayed
showpoint / noshowpointspecifies whether to display the fractional part of a floating point number, when the fractional part is zero
showpos / noshowposspecifies whether to display + for positive numbers
unitbuf / nounitbufspecifies whether the output should be buffered
uppercase / nouppercasespecifies whether uppercase characters should be used in hexadecimal integer and floating-point output
left / right / internalspecifies how a number should be justified
dec / oct/ hexspecifies the notation an integer number should be displayed in
fixed / scientific/
hexfloat(C++11) /
defaultfloat(C++11)
specifies the notation a floating-point number should be displayed in

Input/output streams

C++ input/output streams are primarily defined by iostream, a header file that is part of the C++ standard library (the name stands for Input/Output Stream). In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output. Instead, these are combined as a library of functions. Like the cstdio header inherited from C's stdio.h, iostream provides basic input and output services for C++ programs. iostream uses the objects cin, cout, cerr, and clog for sending data to and from the standard streams input, output, error (unbuffered), and log (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace. [8]

The cout object is of type ostream, which overloads the left bit-shift operator to make it perform an operation completely unrelated to bitwise operations, and notably evaluate to the value of the left argument, allowing multiple operations on the same ostream object, essentially as a different syntax for method cascading, exposing a fluent interface. The cerr and clog objects are also of type ostream, so they overload that operator as well. The cin object is of type istream, which overloads the right bit-shift operator. The directions of the bit-shift operators make it seem as though data is flowing towards the output stream or flowing away from the input stream.

Output formatting

Methods

width(int x)minimum number of characters for next output
fill(char x)character used to fill with in the case that the width needs to be elongated to fill the minimum.
precision(int x)sets the number of significant digits for floating-point numbers

Manipulators

Manipulators are objects that can modify a stream using the << or >> operators.

endl"end line": inserts a newline into the stream and calls flush.
hex"hexadecimal": all further numbers are printed in hexadecimal.
dec"decimal": turns off hexadecimal.
ends"end string": inserts a null character into the stream and calls flush.
flushforces an output stream to write any buffered characters
wscauses an inputstream to 'eat' whitespace
showpointtells the stream to show the decimal point and some zeros with whole numbers

Other manipulators can be found using the header iomanip .

Criticism

The formatting manipulators must be "reset" at the end or the programmer will unexpectedly get their effects on the next output statement.

Some implementations of the C++ standard library have significant amounts of dead code. For example, GNU libstdc++ automatically constructs a locale when building an ostream even if a program never uses any types (date, time or money) that a locale affects, [9] and a statically linked "Hello, World!" program that uses <iostream> of GNU libstdc++ produces an executable an order of magnitude larger than an equivalent program that uses <cstdio>. [10] There exist partial implementations of the C++ standard library designed for space-constrained environments; their <iostream> may leave out features that programs in such environments may not need, such as locale support. [11]

Naming conventions

Examples

The pre-C++23 canonical "Hello, World!" program which used the <iostream> library, can be expressed as follows:

#include<iostream>intmain(){std::cout<<"Hello, world!"<<std::endl;}

This program would output "Hello, world!" followed by a newline and standard output stream buffer flush.

The following example, which uses the <fstream> library, creates a file called 'file.txt' and puts the text 'Hello, world!' followed by a newline into it.

#include<fstream>intmain(){std::ofstreamfile("file.txt");file<<"Hello, world!"<<std::endl;}

Using the <print> library added in C++23 (which is also imported by the standard library module std), the post-C++23 canonical "Hello, World!" program is expressed as:

importstd;intmain(){std::println("Hello, world!");}

Related Research Articles

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class declaration to reference via a generic variable another different class without creating full declaration for each of these different classes.

In computer programming, standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr). Originally I/O happened via a physically connected system console, but standard streams abstract this. When a command is executed via an interactive shell, the streams are typically connected to the text terminal on which the shell is running, but can be changed with redirection or a pipeline. More generally, a child process inherits the standard streams of its parent process.

The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header <stdio.h>. The functionality descends from a "portable I/O package" written by Mike Lesk at Bell Labs in the early 1970s, and officially became part of the Unix operating system in Version 7.

The C standard library, sometimes referred to as libc, is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library.

printf is a C standard library function that formats text and writes it to standard output.

In computing, vectored I/O, also known as scatter/gather I/O, is a method of input and output by which a single procedure call sequentially reads data from multiple buffers and writes it to a single data stream (gather), or reads data from a data stream and writes it to multiple buffers (scatter), as defined in a vector of buffers. Scatter/gather refers to the process of gathering data from, or scattering data into, the given set of buffers. Vectored I/O can operate synchronously or asynchronously. The main reasons for using vectored I/O are efficiency and convenience.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

<i>Modern C++ Design</i> Book by Andrei Alexandrescu

Modern C++ Design: Generic Programming and Design Patterns Applied is a book written by Andrei Alexandrescu, published in 2001 by Addison-Wesley. It has been regarded as "one of the most important C++ books" by Scott Meyers.

scanf, short for scan formatted, is a C standard library function that reads and parses text from standard input.

sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1. The actual number of bits of type char is specified by the preprocessor macro CHAR_BIT, defined in the standard include file limits.h. On most modern computing platforms this is eight bits. The result of sizeof has an unsigned integer type that is usually denoted by size_t.

The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.

In the C++ programming language, seekg is a function in the fstream library that allows you to seek to an arbitrary position in a file. This function is defined for ifstream class - for ofstream class there's a similar function seekp.

The C++ programming language has support for string handling, mostly implemented in its standard library. The language standard specifies several string types, some inherited from C, some designed to make use of the language's features, such as classes and RAII. The most-used of these is std::string.

In the C++ programming language, placement syntax allows programmers to explicitly specify the memory management of individual objects — i.e. their "placement" in memory. Normally, when an object is created dynamically, an allocation function is invoked in such a way that it will both allocate memory for the object, and initialize the object within the newly allocated memory. The placement syntax allows the programmer to supply additional arguments to the allocation function. A common use is to supply a pointer to a suitable region of storage where the object can be initialized, thus separating memory allocation from object construction.

In C++, associative containers are a group of class templates in the standard library of the C++ programming language that implement ordered associative arrays. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. The following containers are defined in the current revision of the C++ standard: set, map, multiset, multimap. Each of these containers differ only on constraints placed on their elements.

Although C++ is one of the most widespread programming languages, many prominent software engineers criticize C++ arguing that it is overly complex and fundamentally flawed. Among the critics have been: Robert Pike, Joshua Bloch, Linus Torvalds, Donald Knuth, Richard Stallman, and Ken Thompson. C++ has been widely adopted and implemented as a systems language through most of its existence. It has been used to build many pieces of important software such as operating systems, runtime systems, programming language interpreters, parsers, lexers, compilers, etc.

<span class="mw-page-title-main">RaftLib</span>

RaftLib is a portable parallel processing system that aims to provide extreme performance while increasing programmer productivity. It enables a programmer to assemble a massively parallel program using simple iostream-like operators. RaftLib handles threading, memory allocation, memory placement, and auto-parallelization of compute kernels. It enables applications to be constructed from chains of compute kernels forming a task and pipeline parallel compute graph. Programs are authored in C++.

<span class="mw-page-title-main">Zig (programming language)</span> A general-purpose programming language, toolchain to build Zig/C/C++ code

Zig is an imperative, general-purpose, statically typed, compiled system programming language designed by Andrew Kelley. It is intended as a successor to the language C, with the intent of being even smaller and simpler to program in, while offering more functionality. It is free and open-source software, released under an MIT License.

C++23 is the name for the version of the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC) 14882 standard for the C++ programming language that follows C++20. The final draft of this version is N4950.

References

  1. ISO/IEC 14882:2003 Programming Languages – C++. [lib.string.streams]/1
  2. Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp.  1109–1112. ISBN   0-201-82470-1.
  3. Bjarne Stroustrup (1997). The C++ programming language (third ed.). Addison-Wesley. pp.  637–640. ISBN   0-201-88954-4.
  4. Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp.  1063–1067. ISBN   0-201-82470-1.
  5. Bjarne Stroustrup. "A History of C++: 1979–1991" (PDF).
  6. Stanley B. Lippman, Josee Lajoie (1999). C++ Primer (third ed.). Massachusetts: Addison-Wesley. pp.  1112–1120. ISBN   0-201-82470-1.
  7. "<ios> Visual Studio 2010". Microsoft MSDN: Visual Studio 2010. Retrieved 28 September 2011.
  8. Holzner, Steven (2001). C++ : Black Book. Scottsdale, Ariz.: Coriolis Group. p. 584. ISBN   1-57610-777-9. ...endl, which flushes the output buffer and sends a newline to the standard output stream.
  9. GNU libstdc++ source code, bits/ios_base.h
  10. C++ vs. C – Pin Eight
  11. "uClibc++ C++ library" . Retrieved 6 January 2012.