WSU logo


College of Engineering & CS
Wright State University
Dayton, Ohio 45435-0001

CEG 333: Introduction to Unix

Prabhaker Mateti

C++ Standard Library


The standard C++ library is a collection of pre-compiled code that any C++ program can use. The library provides basic functionality to interact with the operating system and some standard classes. The library also contains carefully coded versions of well-known algorithms.

The C++ library can be divided into three main groups:

C standard library
This is the library inherited from C by C++. It's available through two sets of headers. The first has the original C names (such as stdio.h, stdlib.h, string.h, time.h, and math.h). The second is named like the rest of the C++ standard (cstdio, cstdlib, cstring, ctime, and cmath) and differs only in that the contents are declared within the std namespace.
iostream library
This provides classes, constants and objects designed to perform input and output operations using streams.
STL (Standard Template Library)
Standard class templates including vectors, queues, lists, strings, sets, maps, etc.

The first two libraries are available not only to programs written in C++ but also other languages such as Pascal, Perl and Python.

Namespaces

All C++ identifiers (such as variables, classes, function names) are defined in a namespace. No two identifiers in the same namespace may have the same name, but different identifiers in non-overlapping namespaces may share one name. Within a namespace, the identifier can be used directly; outside its namespace, the :: operator is used to resolve identifiers. For example, all classes have their own namespace, which is why a class member can have the same name as a global identifier.

Identifiers in the C++ Standard Library are declared in the std namespace. So in a program, they would normally have to be prefixed with std:: (eg, std::cout, std::fprintf, or std::string).

To avoid this, the using keyword tells the compiler to import (or alias) everything in another namespace into the current scope. (That's why so many C++ programs have the line using namespace std;)

Important libc functions

Include stdio.h to use these functions. Note: all libc functions have manpages.

FILE* is a pointer to a special structure describing stream and its file. As always, FILE pointers are defined for the standard files: stdout, stdin, and stderr (these don't have to be opened or closed).

Opening and closing files

Function Syntax Use
fopen FILE *fopen(const char *path, const char *mode); Open a file stream
fclose int fclose(FILE *stream); Close a file stream

mode is a cstring of the format [rwa][+].

Binary I/O

Function Syntax Use
fread size_t fread(void *ptr, size_t size, size_t num_elements, FILE *stream); Read binary data from a stream
fwrite size_t fwrite(const void *ptr, size_t size, size_t num_elements, FILE *stream); Write binary data to a stream

Returns the number of items input/outputted (not the number of characters). If this is less than the expected value, an error occurred.

Formatted I/O

Function Syntax Use
fprintf int fprintf(FILE *stream, const char *format, ...); Write formated data to a stream
fscanf int fscanf(FILE *stream, const char *format, ...); Read formated data from a stream

fprintf returns the number of characters printed, and fscanf the number of variable values assigned. If this is less than the expected value, an error occurred.

format is a cstring containing format directives. All following parameters are correspond to fields in the I/O defined by those directives. There may be any number of directives so long as there is a one-to-one correspondence between the number of variables and the number of fields.

When outputting (fprintf), the values of each variable are converted into strings and substituted, in the order they are given, into the format string.

When inputting (fscanf), the strings at the field positions are converted and stored in order in the variables. A single whitespace character in format matches any whitespace in the input. Scanning stops when the input can't be matched to format or it's fields.

Since scanf needs to alter values, it takes arguments as pointers. Some values, such as cstrings, already are pointers. Other types, such as integers, need to be passed with the "address of" operator (&).

The basic syntax for a directive is %[flags][width][.precision]conversion.

WARNING: when reading a string with fscanf, there must be enough memory allocated to the provided char* for this string and its null terminator. It's a good idea to use the field width for this.

This program (valid in both C++ and C) demonstrates format strings:

      #include <stdio.h>

      int main(int argc, char *argv[]) {
          double d = 0.99;
          char c = 'C';
          char* s = "EG";

          printf("%04i is four characters wide and %f has too many zeros\n", -4, d);
          printf("%.2f%% complete\n", d);
          printf("%c%s\n", c, s);
          s = "%6s\n";
          fprintf(stdout, s, "333");

          return 0;
      }
    

output:

      -004 is four characters wide and 0.990000 has too many zeros
      0.99% complete
      CEG
         333
    

Note: many more advanced options are available to format strings than can be explained here. This includes a way to change the correspondence between fields and parameters. See man fprintf for further reading.

I/O Errors

Function Syntax Use
ferror int ferror(FILE *stream); Return non-zero if the stream has encountered an error
feof int feof(FILE *stream); Return non-zero if the stream has reached the end of its file
clearerr void clearerr(FILE *stream); Clear all errors for the stream