\documentstyle[html]{article}

\sloppy

\newcommand{\tty}[1]{{\bf #1}}

\newcommand{\bs}{{\tt \char'134}}
\newcommand{\nl}{\framebox{\tty{'\bs n'}}}
\newcommand{\nul}{\framebox{\tty{\bs 0}}}
\newcommand{\C}{{\bf C}}
\newcommand{\ch}[1]{\tty{'#1'}}
\newcommand{\cint}{\tty{int}}
\newcommand{\clong}{\tty{long}}
\newcommand{\cchar}{\tty{char}}
\newcommand{\intmax}{{\it int\_max}}
\newcommand{\intmin}{{\it int\_min}}

\newcommand{\typedef}{\tty{typedef}}
\newcommand{\struct}{\tty{struct}}
\newcommand{\cif}{\tty{if}}
\newcommand{\switch}{\tt{switch}}
\newcommand{\while}{\tt{while}}

\renewcommand{\framebox}[1]{#1}

\begin{document}

\title{
The \C\ Standard Library}
\date{March 1995}
\author{Barry McMullin}
\maketitle

\section{Introduction}

It is well known that one should not waste time ~"re-inventing the
wheel"~. In Engineering, this means not redesigning something one
has already got a perfectly satisfactory design for. In Software
Engineering, it means not rewriting software to perform
operations that one has previously written (and tested!) software
for.

In the case of the \C\ language there are a range of things that
programmers very frequently wish to do, which are so common that
standard software for the purpose is actually distributed along
with every \C\ compiler. This software is called the \C\ {\it
Standard Library}. You are more or less guaranteed that every
\C\ compiler will come with an implementation of the Standard
Library. It is important to be aware at least of the existence of
the Standard Library, and to have some outline idea of the
software contained in the Library. In this way you can avoid
unecessarily writing and testing software which is already
effectively available, in a well tested form, for free.

Chapter~10 of {\it Illustrating C}
provides a detailed discussion
of the Standard Library.  You should consult this, or some
equivalent documentation (e.g.\ the on-line help in the Turbo-C++
IDE), whenever you need detailed information on the full range of
functionality of the Standard Library. This essay is intended
only to provide an introduction to a very small subset of the
Standard Library, and is not a substitute for those more detailed
sources of information.

\section{Mechanics}

In order to use the facilities of the Standard Library, one must
have some understanding of the mechanics of how the compiler will
access it.

Some very simple \C\ programs can be
completely
~"self-contained"~: all the code for all the functions was
contained in a single program file. In general, however, this
need not be the case; in particular, it will not be the case if
you wish to make use of the Standard Library.

In principle, of course, the Standard Library {\it could\/} be
distributed simply as a set of one or more \C\ source code files.
You would then use a library function simply by copying the
source code out of the relevant library file and pasting it into
your own program file. However, this is {\it not\/} the mechanism
which is used in practise for a variety of reasons:

\begin{itemize}

\item Since the code for the Standard Library is rarely if ever
modified, it is very inefficient to have to recompile or
retranslate it every time a programmer makes a change to his own
code.

\item The library functions are, in some cases, not actually
written in the \C\ language at all.

\item The compiler suppliers normally prefer not to distribute
source code for the Standard Library as this would facilitate
unscrupulous pirating of their work.

\end{itemize}

What is actually done is that the Standard Library software is
distributed in a sort of ~"canned"~ or {\it precompiled\/} form,
as a set of ~"object files"~ (or, more commonly, a single
~"object library"~ file). Your program file(s) are then compiled
completely separately from the source code for the Standard
Library, yielding one or more further object files. Finally, all
the required ~"object"~ files, both your own, and those making up
the Standard Library, are combined or {\it linked\/} together to
yield the ~"executable"~ file, which can actually be run.

To a large extent this process can be made automatic and
invisible. The compiler compiles your source file(s) to the
~"object"~ code form, and then automatically links these together
with the any required library object file(s).

However, it cannot be made {\it completely\/} automatic. In
practise there is certain information, associated with the
Standard Library, which the compiler {\it must\/} be made aware
of at the time it is compiling {\it your\/} source files, in
order to make sure that the object files produced will correctly
link up with the object files for the Standard Library.

Since, for the most part, the Standard Library simply consists of
a set of {\it functions\/} which you can call in your program,
the most important such information is the way data is to
be exchanged with each such function; i.e.\ how many {\it
parameters\/} does the function take, of what types, in what
order, and what type of \tty{return} value does the function
yield (if any)?

The compiler could, of course, try to infer this information from
the way the function is actually called; but this is not always
technically possible, and, in any case, it is much better if
the compiler has some {\it independent\/} way of knowing how the
function should be called, because then it can automatically
check whether you have, in each case, called it correctly. It
turns out that this is extremely useful, and is an effective way
of automatically detecting a range of very common programming
mistakes.

The compiler is given this information about how a function
should be called by the use of a so-called {\it function
prototype}. This is simply the ~"header"~ of the function
definition, which states the function name, the \tty{return}
type, and the formal parameter list. But whereas, in a function
definition this is then followed by a compound statement which
actually defines the function, in a function prototype it is
simply followed by a terminating semicolon. Thus, a prototype
might look like this for example:

\begin{verbatim}
    int multiply(unsigned *multiplicand,
      unsigned multiplier, unsigned *product);
\end{verbatim}

This tells the compiler that the function called
\verb$multiply$ should take three parameters, repectively of
types \tty{(unsigned~*)}, \tty{unsigned} and \tty{(unsigned~*)}, and
will yield a \tty{return} value of type \cint. Function
prototypes should appear at the outermost level of a source
file~-~i.e.\ not within the definition of any function.

So far, so good. It seems that if you wish to call or invoke any
of the Standard Library functions in your program,, you must
simply insert, somewhere before the function(s) which make such
call(s), a suitable function prototype, so that the compiler will
then be able to decide whether the calls are correct or not.

But how are you going to know what is the correct prototype for
each function in the first place?

Well, one possibility is to look up the function in the detailed
technical documentation for the Standard Libarary: this will
normally include the function prototype.  You can then copy that
into your own file.

However, this is clearly unsatisfactory.  Apart from being
laborious, it is error prone~-~and the possibility of an error in
the function prototype undermines a primary point of using
prototypes in the first place, namely that it allows the compiler
to crosscheck for valid function calls!  A better idea is if the
prototypes are provided to you in a machine readable form~-~i.e.\
in one or more files on the computer. Then you can simply copy
the required ones, and paste them into your own source files.

Well, yes, this is a major improvement, but still leaves
something to be desired. For one thing, duplicating the
prototypes in every source program wastes disk space. More
seriously, there is always a danger that you might (accidentally)
modify a prototype, again confounding the idea of allowing the
compiler to automatically crosscheck the prototype against the
invocation(s) of the function.

A final possibility is to leave the prototypes in one or more separate
files; but have the compiler automatically access or scan the
relevant files immediately before, or as part of the process of,
compiling {\it your\/} files.  In this way, there is no
laborious, manual, copying of the prototypes, but no duplication
and no risk of accidental modification either.

Files which are used for this kind of purpose~-~which contain no
actual executable code, but which contain only function prototypes
(and possibly other things such as symbolic constants etc.) which
allow the compiler to correctly mesh the file it is compiling
with some other software which has been ~"pre-compiled"~, are
called {\it header\/} files. Header files are normally given the
extension \framebox{\tty{.h}} to distinguish them from files which actually
contain executable code~-~function definitions etc.~-~which will
normally have the extension \framebox{\tty{.c}}~.

It would be possible, in principle, to put all the prototypes for
all the functions in the Standard Library, plus any other
required information (sybolic constants etc.), in a single
\framebox{\tty{.h}} file, and have the compiler automatically include it in
compiling any file. However, in practise this is not done for
various reasons. For example, most \framebox{\tty{.c}} files only involve
calling a small subset of the functions in the Standard Library;
it is then wasteful and time consuming for the compiler to
process prototypes for {\it all\/} functions in the Standard
Library.

The mechanism that is actually used then is as follows.  A series
of separate \framebox{\tty{.h}} files are supplied with the compiler. Each
one provides prototypes (plus other required information) relating
to only some coherent or related {\it subset\/} of the functions
in the Standard Library. The programmer must then explicitly
instruct the compiler to process just those \framebox{\tty{.h}} files which
are required in order to properly compile any particular \framebox{\tty{.c}}
file.  And this is done by inserting, into the \framebox{\tty{.c}} file one
or more so-called \verb$#include$ directives. A \verb$#include$
directive is something much the same as a \verb$#define$ in the
sense that it is not handled by the compiler ~"proper"~ but by
the ~"pre-processor"~ which runs (automatically) immediately
before the compiler.  In this case, the pre-processor processes a
\verb$#include$ by concatenating together the \framebox{\tty{.h}} file and
the original \framebox{\tty{.c}} file, to produce a big temporary file which
is what is actually then processed in the compilation phase proper.

Thus, if you want to use a function from the Standard Library,
you must first look up, in the relevant technical documentation,
\pagebreak
which header file contains the prototype etc.\ for that function;
and then insert a line something like the following in your
\framebox{\tty{.c}} file:
\begin{verbatim}
        #include <stdio.h>
\end{verbatim}

The angle brackets around the name of the header file tell the
pre-processor to search for the file in the ~"standard"~
directories for such things; normally these will be set up when
the compiler is installed, and you, as a programmer, need not
worry about what these standard directories actually are.
However, in case you wish to actually examine any of the header
files, the relevant directory for Turbo-C++, as configured on the
machines in the CAE Laboratory is:

\begin{verbatim}
        F:\TC\INCLUDE
\end{verbatim}

You may, of course, need to \verb$#include$ several header files,
depending on the particular selection of Standard Library
functions you wish to use.

All required \verb$#include$ directives are normally placed close
to the top of your \framebox{\tty{.c}} file~-~typically either at the very
top, or immediately after an initial introductory comment which
documents the overall contents of the source file. Each
\verb$#include$ {\it must\/}, in any case, preceed any calls or
invocations of the relevant functions.

The rest of this essay is concerned with introducing just a very
small selection of the several hundred functions normally
available in the Standard Library. It is organised into sections
according to the distinct \framebox{\tty{.h}} files required.

\section{Implementation-defined Limits: \tty{limits.h}}

The header file \tty{limits.h} essentially just provides
\verb$#define$ directives defining symbolic constants for the
maximum and minimum values allowed with the standard \C\ integral
data types~-~i.e.\ it does not provide any function prototypoes
as such. It is important to be able to refer to these values in
your programs in order to prevent, or at least detect, overflow
situations. The values potentially differ from one \C\ compiler
to another (hence ~"implementation-defined"~), but the symbolic
constants defined in \tty{limits.h} always have the same names.
Thus by using the symbolic constants to refer to these limits it
should be possible to write your programs in such a way that they
will automatically adjust to whatever the limits actually are
with any particular compiler.

\newpage
Some constants which are commonly used are:

\bigskip
\begin{tabular}{ll}
\tt INT\_MAX     & maximum value of \cint \\
\tt INT\_MIN     & minimum value of \cint \\
\tt LONG\_MAX    & maximum value of \clong \\
\tt LONG\_MIN    & minimum value of \clong \\
\tt UINT\_MAX    & maximum value of \tt unsigned int \\
\tt ULONG\_MAX   & maximum value of \tt unsigned long \\
\end{tabular}
\bigskip

This is not an exhaustive list: examine a copy of \tty{limits.h}
for yourself to see others. However, note that there is, of
course, no need for constants called, say, \tty{UINT\_MIN} or
\tty{ULONG\_MIN} since these minima are always guaranteed to be
simply zero.

\section{Error Conditions: \tty{errno.h}}

Many functions in the standard library will detect ~"exception"~
or ~"error"~ conditions in certain circumstances~-~essentially if
the function has been requested to do something which, for some
reason, it can't. The exact action of the function in such
situations depends on the details of the particular function and
the particular exception condition. However, the most usual
strategy is for the \tty{return} value from the function to
signal, with some special value, that something has gone wrong.
It is then up to the calling site to react to this in some
~"appropriate"~ way.  Minimally this will mean giving some kind
of overt external signal of the problem.

In any case, while the standard library functions typically provide
an initial or gross indication that something has gone wrong via
the \tty{return} value, it is often also useful for the calling
site to have access to a more detailed signal which clarifies
exactly the nature of the problem. This is usually achieved by
having the standard library function record a detailed ~"error
number"~ in a global \cint\ variable called \tty{errno}.  This
variable is defined within the standard library itself: but your
programs can gain access to it by a so-called \tty{extern}
declaration. This declaration is already provided in the header
file \tty{errno.h}; so if you \verb$#include$ this, you will then
be able to access \tty{errno} just as any other variable is
accessed. By examining its value immediately after a call to a
standard function, your program can generally establish what (if
anything) went wrong. 

As well as the declaration of \tty{errno} the file \tty{errno.h}
also provides a series of \verb$#define$ directives which define
symbolic names for the standard error numbers or codes which may
be recorded in \tty{errno}. This would allow your program to test
for specific error codes by comparing \tty{errno} to these
symbolic values. We shall also see later how \tty{errno} can be
automatically translated into a corresponding textual error
~"message"~, and, say, displayed, on the computer screen (see the
discussion of the function \tty{perror()}, prototyped in
\tty{stdio.h}).

\section{Utility Functions: \tty{stdlib.h}}

The header file \tty{stdlib} provides prototypes for a selection
of miscellaneous ~"utility"~ functions, as well as a few more
symbolic constants. A small selection of the more commonly used
functions is as follows:

\subsection*{\tt int atoi(char *s)}

This takes a string representation of an integer (i.e.\ a string
something like \tty{"145"} or \tty{"-9999"} or \tty{"000000"}
etc.) and converts it into the corresponding internal
representation of type \cint, which is the \tty{return} value
from the function.

With the Turbo-C++ implementation of the Standard Library, the
behaviour where the answer would overflow (e.g.\
\tty{atoi(100000)}) is indeterminate~-~so it is {\it your\/}
responsibility to make sure this never arises; if the conversion
simply cannot be done (e.g.\ \tty{atoi("xyz")} the \tty{return}
value will be \tty{0}.

\subsection*{\tt long atol(char *s)}

This takes a string representation of an integer (i.e.\
a string something like \tty{"145"} or \tty{"-999999"} or
\tty{"25763178"} etc.) and converts it into the corresponding
internal representation of type \clong, which is the \tty{return}
value from the function. Leading white space in the string is
ignored.

Again, with the Turbo-C++ implementation of the Standard Library,
the behaviour where the answer would overflow (e.g.\
\tty{atol(-500000000)}) is indeterminate; and if the conversion
simply cannot be done (e.g.\ \tty{atol("")} the \tty{return}
value will be \tty{0L}.

\subsection*{\tt void exit(int status)}

This function may be called to forcibly terminate the program at
any point. The parameter \tty{status} is simply a number which
is, in some sense, made available to the ~"external"~ environment
of the program.\footnote{In the case of programs run under
  \tty{DOS}, the \tty{exit()} status can be accessed
  via the \tty{errorlevel} parameter in the \tty{DOS} \tty{if}
  command~-~though this is normally only used in batch
  files.}
In any case, if you are using \tty{exit()} to terminate your
program, you should normally just give it one of two pre-defined
exit values which have been given symbolic names in
\tty{stdlib.h}: use \tty{exit(EXIT\_SUCCESS)} if the program is
terminating ~"normally"~ and \tty{exit(EXIT\_FAILURE)} if it is
terminating because of some unexpected or intolerable exception
or error being encountered.

\section{Input and Output: \tty{stdio.h}}

\tty{stdio.h} (~"standard input/output"~) provides basic
functions for accessing data ~"external"~ to a program. This
naturally includes data in files on disk, but also covers data
coming from the keyboard, or displayed on the screen, or data
routed via any of the other input/output ~"ports"~ of the
computer. All of these sources or destinations for data may be
generically referred to as {\it streams}, or, more simply, {\it
files}.

Files are classified into two kinds: {\it text\/} and {\it
binary}. A text file is divided into ~"lines"~, where each line
has zero or more characters, and is terminated by a newline
character \nl~. A binary
file is simply a sequence of
unprocessed or uninterpreted bytes, with no line organisation
superimposed upon it.\footnote{In general, the terms {\it
  character\/} and {\it byte\/} can be regarded as almost
  synonymous here.}

Files are accessed through data structures called {\it file
pointers}. Technically, a file pointer is the address of an
object of a special type, denoted \tty{FILE}. This type is
defined by the \tty{stdio.h} header file, and will not be
recognised by the compiler unless the header file has been
\verb$#include$'d.

A file pointer {\it must\/} be created and associated with each
particular external disk file, or input/output port, before any
data in that file can be accessed (~"read"~ or ~"written"~). This
process of creating a file pointer and associating it with a disk
file or input/output port is called {\it opening\/} a file, and
is performed by the \tty{fopen()} function described in more
detail below. The \tty{return} value from \tty{fopen()} is the
value of the file pointer, and must be stored in a suitable
variable to allow the file to be accessed subsequently.

Files are opened for access in a particular {\it mode\/}:
reading, writing, or (occasionally) both. The file is treated as
a {\it sequence\/} of characters (or, more generally, bytes).
When the file is first opened it is positioned at the very start;
the contents can then be read or written in sequence until the end of
the file. With certain kinds of file (namely those stored on
disk) it may be possible to ~"reposition"~ the file in an arbitrary
way~-~go back to the start, or directly to the end, etc. If a
file if opened for writing then its previous contents, if any,
will normally be lost.

A program may have many files open at any given time, each one
associated with its own distinct file pointer.

File contents can be read, one character at a time, in sequence,
with the \tty{fgetc()} function (provided the file is in read
mode); or written with the \tty{fputc()} function (in write
mode). There are also a variety of more sophisticated reading and
writing functions such as \tty{fprintf()} and \tty{fscanf()},
which typically read or write many characters in one go, and
automatically translate between external ~"text"~
representations, and internal ~"binary"~ representations, for the
various native data types (\cint, \clong\ etc.).

When reading a file it is necessary to be able to recognise when
the end of the file is encountered. This is signalled by
\tty{fgetc()} yielding a special, reserved, \tty{return} value,
with the symbolic name \tty{EOF} (this value is also~-~somewhat
misleadingly~-~the \tty{return} value if \tty{fgetc()} encounters
any kind of error or exception condition).

Now this raises a problem: if a special value is reserved to
denote the end of file condition, does this mean that this
special value can never actually be stored {\it within\/} a file
(since, once it is read, it would be mistakenly taken as
signalling that the file is ended)? If so, this would be a
serious restriction.

In practice, this problem is solved in a rather ingenious, but
also subtle and confusing manner. A file is treated as a sequence
of values of type \cchar; but the \tty{return} value from
\tty{fgetc()} is actually made of type \cint. Normally this is
just an ~"encoded"~ or ~"numerical equivalent"~ of the \cchar\
value read from the file. But since \cint\ supports more distinct
values than \cchar\ does, it is possible to encode \tty{EOF} as a
\cint\ value than has {\it no\/} ~"equivalent"~ in the \cchar\
data type. In this way, a file can contain {\it any\/} arbitrary
\cchar\ values, without restriction. But, in turn, this means
that it is very important that before the \tty{return} value from
\tty{fgetc()} is transformed back into a \cchar\ value (e.g.\ by
assigning it to a variable of type \cchar) it must be tested to
see is it \tty{EOF}.

For consistency with this behaviour of \tty{fgetc()} many
other functions in the Standard Library (such as \tty{fputc()}
for example) also use the \cint\ data type to effectively deal
with \cchar\ values, but allowing also for the special \tty{EOF}
value.

As I said, this mechanism is quite subtle; in my opinion it may
be just a little bit {\it too\/} subtle! It involves the
programmer in relying, willy nilly, on automatic conversions
between types~-~a practice of which I am generally severely
critical. Unfortunately, this is now a {\it de facto\/}
standardised way of doing things with the Standard Library, and
cannot be helped at this stage. Nonetheless, it certainly helps
if you at least understand what is going on.

Once the program is finished processing a particular file, the
file should be {\it closed\/} with the \tty{fclose()} function.
This essentially involves discarding the data structure of type
\tty{FILE} which was associated with the file: it is therefore
very important that, once a file is closed, the file pointer which
was associated with it is not used again (since it no longer
points at anything meaningful!). Files are automatically closed
when a program terminates in a ~"controlled"~ fashion (either by
reaching the end of the \tty{main()} function, or by an explicit
invocation of the \tty{exit()} function).

There are three files which are opened by default, and
automatically, for every program. File pointers associated with
them are defined in \tty{stdio.h}, as follows:
\begin{description}
\item \tty{stdin}~: The {\it standard input file}. By default
this is a read mode file, associated with the computer keyboard.
However, if the program is invoked from the \tty{DOS} command
line, then this file may be ~"redirected"~ to be associated with,
say, a disk file, using the \tty{DOS} input redirection
operator~\framebox{\tty{<}}~.
\item \tty{stdout} : The {\it standard output file}. By default
this is a write mode file, associated with the computer display
screen.\footnote{When running a program under the Turbo-C++ IDE,
  this corresponds to the so-called \tty{User screen}, which can
  be accessed via the \tty{Window} pull-down menu.}
Again, however, if the program is invoked from the
\tty{DOS} command line, then this file may be ~"redirected"~ to
be associated with, say, a disk file, using the \tty{DOS} output
redirection operator \framebox{\tty{>}}~.
\item \tty{stderr} : The {\it standard error file}. This is a
write mode file, associated with the computer display screen.
It differs from \tty{stdout} in that it cannot be redirected in
any simple way under \tty{DOS}.
\end{description}

A program can do input and output on these three files
immediately, without having to call \tty{fopen()} first. The
three files have certain conventional usages, as the names imply.
Thus many programs take one input file,
or stream of data, and transform it in some way into one
output stream of data. If this is the case, the input data would
normally be read from \tty{stdin}, and the output data would be
written on \tty{stdout}. \tty{stderr} is reserved for signalling
~"errors"~ or exception conditions, separate from the ~"normal"~
output. Programs written in this way can then be conveniently
connected together in ~"pipelines"~, with the output from one
being automatically routed as the input to another; in \tty{DOS}
pipelines are set up with the pipe operator \framebox{\tty{|}}~.

Thus, for example, suppose we have two programs \tty{part1} and
\tty{part2} which perform two separate transformations on a
data stream. The simple (\tty{DOS}) command:
\begin{verbatim}
        D:\ part1
\end{verbatim}
would cause \tty{part1} to be started up, reading its input from
the keyboard, and writing its output to the
screen.\footnote{Incidentally, when input is being taken from the
  keyboard, under \tty{DOS}, the special key combination
  \tty{CTRL-Z}, followed by \tty{Enter}, is normally used to signal
  end of file.}

\newpage
By contrast, the command:
\begin{verbatim}
        D:\ part1 <in.dat >out.dat
\end{verbatim}
would cause \tty{part1} to read its input from the disk file
\tty{in.dat} and write its output to the disk file \tty{out.dat}.
Note that, despite the redirection of \tty{stdout}, any error or
exception messages, written to \tty{stderr}, would still appear
on the screen.

Finally, the command:
\begin{verbatim}
        D:\ part1 <in.dat | part2 >out.dat
\end{verbatim}
would cause the output of \tty{part1} to be automatically routed
as the input to \tty{part2}, whose output would then finally be
routed to \tty{out.dat}.

Thus, writing programs to take input from \tty{stdin} and write
output to \tty{stdout} (and errors etc.\ to \tty{stderr}) means
that they can be subsequently mixed and matched in a very
flexible way to achieve a variety of different effects, and is a
very powerful idea. But even if you have no intention of
linking programs in this way, it will still often be convenient
to use \tty{stdin} as a source of keyboard input, and
\tty{stdout} (and/or \tty{stderr}) as a route for output to the
screen. There are specialised versions of several \tty{stdio.h}
functions which access one or the other of these files by default
(e.g.\ \tty{printf()} is a variant of \tty{fprintf()} which
automatically writes to \tty{stdout}).

A small subset of the functions declared in \tty{stdio.h} will
now be described in more detail.

\subsection*{\tt FILE *fopen(char *filename, char *mode)}

\tty{fopen()} is used to create a file pointer or stream, for
subsequent input or output to a file. Thus, the \tty{return}
value from \tty{fopen()} must normally be stored in a variable, so
that it can then be used as an argument to other functions such
as \tty{fgetc()} etc.

\tty{filename} is a string giving the name of the desired file.
This should conform to the conventions of the ~"environment"~ or
~"operating system"~ under which the program will be running.
Under \tty{DOS}, file names consist, in general, of a device
specifier (e.g., \framebox{\tty{D:}} ), followed by a ~"path"~ identifying
the desired subdirectory, followed by an individual file name
proper. Directory and file names proper consist of a name part of
up to 8 characters, followed by a period, followed by an
~"extension"~ part of up to three characters. \tty{DOS} does not
distinguish between upper and lower case anywhere in a file name.
The directory separator character in \tty{DOS} is the backslash
\verb$\$ ; this is a rather unfortunate historical
accident, as this character also has a special meaning in \C\
strings, as an ~"escape"~ character. The nett effect is that, in
representing a \tty{DOS} file name in a \C\ string constant, you
must write the directory separator as a {\it double\/} backslash:
\verb$\\$ ; note that this actually only results in the
internal {\it storage\/} of a single character within the string,
when the program is compiled.

Examples of well formed \tty{filename} arguments under \tty{DOS}
might be:
\begin{verbatim}
        "myfile"
        "yourfile.h"
        "d:something.xyz"
        "f:\\tcPP\\INClude\\stdio.H"
        "COM1:"
        "lpt1:"
\end{verbatim}

Of course the \tty{filename} argument, as with any of the other
string arguments to be discussed, might equally be a string
~"variable"~~-~the name of a \cchar\ array which had previously
been loaded with the desired file name (including the usual nul
character as the string terminator: \nul~).

\tty{mode} is a string specifying the desired file ~"access
mode"~~-~i.e.\ what kind(s) of operations are going to be carried
out on it. Two examples of legal values for this would be:

\begin{description}
\item \tty{"r"} : Open the file for reading.
\item \tty{"w"} : Open the file for writing.
\end{description}

In general, \tty{fopen()} will open a file for access
either as a binary or a text file~-~but the default
is implementation specific. Under Turbo-C++, this default can be
configured by the user.  In any case, regardless of the default,
the type of access can be explicitly specified in the \tty{mode}
string by adding either a \tty{t} or \tty{b} character for text
or binary respectively, e.g.:

\begin{description}
\item \tty{"rt"} : Open for reading as a text file.
\item \tty{"wb"} : Open for writing as a binary file.
\end{description}

If the call to \tty{fopen()} is successful, then the \tty{return}
value is simply the value of the created file pointer. However,
if the call fails for any reason (e.g.\ trying to open a file on
device \tty{"X:"} when no such device is present on the machine)
then the \tty{return} value will be the special zero or {\it
null\/} pointer value defined in \C. \tty{stdio.h} (and, indeed,
several of the other header files) define the symbolic name
\tty{NULL} for this value. Thus, after a call to \tty{fopen()}
your program should always check the \tty{return} value to see
whether it is \tty{NULL}~-~and take some appropriate action
if so (e.g.\ issue a suitable message and call \tty{exit()}). In
any case, if the \tty{return} value from \tty{fopen()} {\it is\/}
set to \tty{NULL} then \tty{errno} will also be set to some more
specific error code.

\subsection*{\tt int fgetc(FILE *stream)}

\tty{fgetc()} reads the next sequential character (byte) from the
open file identified by the file pointer \tty{stream}. This
character is converted into an \cint\ value, and is the
\tty{return} value from the function. However, if the end of file
is encountered (the last character has already been read), or if
any other error is encountered in reading, then the \tty{return}
value will be \tty{EOF}, and \tty{errno} will be set
appropriately. In the case of a text file, the newline character
\nl\ should be interpreted as terminating a line.

\subsection*{\tt int getchar(void)}

\tty{getchar()} is equivalent to \tty{fgetc(stdin)}.

\subsection*{\tt int fputc(int c, FILE *stream)}

\tty{fputc()} converts the \cint\ value \tty{c} into the
corresponding \cchar\ value, and writes that to the next
sequential position in the open file identified by the file
pointer \tty{stream}. The \tty{return} value is normally set to
be equal to the input argument \tty{c}; however, if any error is
encountered then the \tty{return} value will be \tty{EOF} and
\tty{errno} will be set appropriately.

\subsection*{\tt int putchar(int c)}

\tty{putchar(c)} is equivalent to \tty{fputc(c, stdout)}.

\subsection*{\tt int fprintf(FILE *stream, char *format, ...)}

\tty{fprintf()} is a ~"print-and-format"~ function. It
provides for transformation of values of any of
the native \C\ data types into a corresponding textual or string
form; this whole string is written to the open file
identified by the file pointer \tty{stream}.
\tty{fprintf()} is actually just one of a whole family of
functions which provide minor variations on the basic idea of
formatted output.

\tty{fprintf()} takes a {\it variable\/} number of arguments. The
arguments \tty{stream} and \tty{format} are {\it
required\/}~-~they {\it must\/} always be present and must be of
the types specified in the prototype; but these may then be
followed by an arbitrary number (including zero!) of further
arguments of arbitrary types.

\tty{format} is a string which indirectly specifies how many
further arguments are being passed in (if any) and their types.

More precisely, \tty{format} contains ~"ordinary"~ characters
interspersed with ~"conversion specifications"~. The ordinary
characters are simply written to \tty{stream}. But each time
\tty{fprintf()} encounters a conversion specification, another
input argument is converted into a textual or string form, and
output on \tty{stream} instead.

Thus, to simply print a string on the screen (and assuming that
\tty{stdout} has not been redirected) one might use the function
call:

\begin{verbatim}
        fprintf(stdout, "Helllooo VietNAM!!!!!!")
\end{verbatim}

Conversion specifications are introduced by the character
\framebox{\tty{\%}}~. Examples of some simple conversion
specifications are as follows:

\begin{description}
\item \verb$"%d"$ Convert an \cint\ value to a normal (base 10) textual
representation.
\item \verb$"%u"$ Convert an \tty{unsigned int} value.
\item \verb$"%ld"$ Convert a \clong\ value.
\item \verb$"%c"$ ~"Convert"~ a \cchar\ value.
\item \verb$"%s"$ ~"Convert"~ a string value (i.e.\ the argument should
be technically of type \tty{(char *)} and point at a normal
nul-terminated array of characters).
\end{description}

In the last two cases, the argument is already essentially
textual, so there is strictly no ~"conversion"~ to be done as
such.

There are many other more complex conversion specifications, but
they will not be detailed here.

Examples of the use of \tty{fprintf()} might be as follows:
\begin{verbatim}
        fprintf(stdout, "The answer is: %d.", 42);
\end{verbatim}

It is important to understand that although the \cint\ value
\tty{42} appears in texual form in the \C\ statement above, when the
program is compiled this is converted into an internal,
non-textual, representation. This is why, in order to display
this value on the screen again, \tty{fprintf()} must be used to
convert back to a textual representation. In this case the nett
effect of this call to \tty{fprintf()} will be that the string:
\begin{verbatim}
        The answer is: 42.
\end{verbatim}
will appear on the screen (assuming \tty{stdout} has not been
redirected). Precisely the same display would, of course, result
from the statement:
\begin{verbatim}
        fprintf(stdout, "The answer is: %d.", 7 * 6);
\end{verbatim}

\newpage
Again, the same display would result from the sequence of statments:
\begin{verbatim}
        x = 7;
        y = x;
        x--;
        y++;
        fprintf(stdout, "The answer is: %d.", (y * x) - 6);
\end{verbatim}
where \tty{x} and \tty{y} are \cint\ variables. Similarly, if
\tty{a}, \tty{b} and \tty{c} are variables of type \cint,
\clong\ and \cchar\ respectively, we might encounter the sequence
of statements:
\begin{verbatim}
        a = 32000;
        b = 32000L * 32000L;
        c = '!';
        fprintf(stdout, "%d times %d is %ld%c", a, a, b, c);
\end{verbatim}
resulting in the following message on the screen:
\begin{verbatim}
        32000 times 32000 is 1024000000!
\end{verbatim}

Note carefully, how the extra arguments in the call to
\tty{fprintf()} {\it must\/} pair off exactly with the conversion
specifications in the \tty{format} argument: i.e.\ for each
conversion specification, in sequence, which appears in the
\tty{format} string, there must be one extra argument, of just
the right type. For technical reasons, which will not be explored
here, {\it it is not possible for the computer to automatically
check that conversion specifications do, in fact, match up with
arguments correctly}. A mismatch between conversion
specifications and arguments in a call to \tty{fprintf()}, or
some related function, is one of the most common kinds of errors
encountered in \C\ programs~-~precisely because the computer
cannot automatically detect it. The effects of such errors are
completely unpredictable, and may not be {\it immediately\/}
apparent at all, so that they can be extremely difficult to track
down. You have been warned!

Some trivial examples of such mismatching would be as follows:
\begin{verbatim}
        fprintf(stream, "The answer is: %d", 42L);

        fprintf(stream, "Or perhaps it is: %l", 42);

        fprintf(stream, "Or there again, maybe its %d");

        fprintf(stream, "My last offer is: %d", 42, 53);
\end{verbatim}

Note that if you want to move onto a new line on the display
screen, you must explicitly write the newline character
\nl\ to the relevant stream. Try to predict the
precise effect of this sequence of statements for example:
\begin{verbatim}
        fprintf(stdout, "Hello. ");
        fprintf(stdout, "Hello?");
        fprintf(stdout, "\nIs that you?");
        fprintf(stdout, "Yes?\nNo...\n\nMaybe????\n");
        fprintf(stdout, "My number is:\n%d\nnWhat's yours?", 42);
\end{verbatim}

Note that because the \framebox{\tty{\%}} character in the
\tty{format} string is interpreted in a special way by
\tty{fprintf()} (namely as introducing a conversion
specification), there is a problem if one actually wants to just
output this character. To get around this you just put in two
successive \framebox{\tty{\%}} characters, thus:
\framebox{\tty{\%\%}}~. The second one will cause \tty{fprintf()}
to recognise that this is not a conversion specification after
all, and it will simply output one \framebox{\tty{\%}} character
without further ado (and without attempting to convert any
argument).

The \tty{return} value from \tty{fprintf()} is the number of
characters which have been written out, or \tty{EOF} if any error
has been detected. \C\ programmers commonly neglect to check this
\tty{return} value from \tty{fprintf()}, presumably because error
conditions which it can detect and signal are rather rare.
Nonetheless, as a general practice I would recommend that you
include code in your programs to check this \tty{return} value (at
least to see if it is \tty{EOF}), unless the your usage is
extremely trivial (e.g.\ just printing the \tty{format} string,
without having any extra arguments to be converted).

\subsection*{\tt int printf(char *format, ...)}

\tty{printf(format, ...)} is equivalent to \tty{fprintf(stdout,
format, ...)}.

\subsection*{\tt int fscanf(FILE *stream, char *format, ...)}

\tty{fscanf()} is more or less the converse to \tty{fprintf()}:
it reads characters from \tty{stream} and attempts to convert
them into ~"internal"~ representations of appropriate types, as
determined by conversion specifications in the string
\tty{format}. {\it The extra arguments must all be pointer types in
this case}. Typicllly, these arguments will simply be the
addresses of variables (generated with the \framebox{\tty{\&}}
operator) into which the converted values are to be stored.
\tty{fprintf()} thus simply stores each converted value at the
location pointed at by each extra argument in turn.  Again, it is
up to you, the programmer, to ensure that the arguments match the
conversion specifications correctly; and again, if they do not,
then this will {\it not\/} be automatically detected, and will have
entirely unpredictable effects.

The conversion specifications handled by \tty{fscanf()} are quite
similar in format to those handled by \tty{fprintf()}. They will
not be described further here.

The \tty{return} value from \tty{fscanf()} is the number of input
fields or values successfully scanned, converted, and stored, or
\tty{EOF} if end of file or any error is encountered. In general,
it is a very good idea for your programs to check this
\tty{return}
value to see that it has the expected value.

\subsection*{\tt int scanf(char *format, ...)}

\tty{scanf(format, ...)} is equivalent to \tty{fscanf(stdin,
format, ...)}.

\subsection*{\tt int fclose(FILE *stream)}

\tty{fclose()} simply closes the open file associated with
\tty{stream}. The \tty{return} value is zero if this is completed
successfully; otherwise it is \tty{EOF} and \tty{errno} is set.

While open files {\it should\/} be closed automatically if or
when your program exits anyway, it is still a good practice to
explicitly close files with \tty{fclose()} when your program is
finished with them. This makes the behaviour of the program more
intelligible to someone reading it, and also provides a little
extra ~"robustness"~ against the possibility that your program
might terminate abnormally (i.e.\ CRASH!).

\subsection*{\tt void perror(char *s)}

\tty{perror(s)} outputs the string \tty{s} on \tty{stderr},
followed by an error message which describes or elaborates the
error code currently stored in \tty{errno}.  It is
equivalent to:
\begin{quote}
\verb$fprintf(stderr, "%s: %s\n", s, "${\it error
message\/}\verb$")$
\end{quote}
where {\it error message\/} is a string describing whatever error
condition is represented by the current value of \tty{errno}.

\tty{perror()} might usefully be called on any occasion when your
program detects that a standard library function has failed to
operate as expected.
\newpage
\section{Diagnostics: \tty{assert.h}}

\tty{assert.h} provides the declaration of one ~"function-like"~
object with the following prototype:

\subsection*{\tt void assert(int status)}

For technical reasons, this object is {\it not\/} implemented as
a function in the normal sense, but is what is called a {\it
macro\/} instead. However, for most practical purposes, it can be
regarded just as any ~"normal"~ function.

If \tty{status} is non-zero then \tty{assert()} will have no
effect; but if \tty{status} is zero then a message of the
following form will be output to \tty{stderr}:
\begin{quote}
\verb$Assertion failed: $ {\it status}\verb$, file ${\it
filename}\verb$, line ${\it nnn}
\end{quote}
where {\it status\/} is the value of \tty{status} (i.e.\ zero),
{\it filename\/} is the name of the source file containing the
call to \tty{assert()}, and {\it nnn\/} is the line number in
that file at which the call appears. \tty{assert()} then causes
the program to terminate.

\tty{assert()} is potentially a very useful way of dealing with
error or exception conditions detected within your programs, where
the condition is such that you are unable (or unwilling) to try
to make the program deal with it in any more ~"intelligent"~ way.
The beauty of \tty{assert()} is that, if it is activiated, the
resulting message immediately pinpoints exactly the position in your
source code where the problem is detected. However, note that
this benefit will be almost totally lost if you place the
invocation of \tty{assert()} within a function of your own, which
you then call from wherever the error is detected: for then the
file name and line number output by \tty{assert()} will always be
the same (namely within your error handler) and will not give any
indication of the ~"real"~ position at which the problem was
detected.

\section{Character Class Tests: \tty{ctype.h}}

\tty{ctype.h} provides prototypes for a selection of functions
which test a \cchar\ value for membership of a given class. In
each case the function takes a single argument, which is technically
of type \tty{int}, but which represents a \cchar\ value or,
possibly, \tty{EOF}; this is for compatibility with \tty{fgetc()}
as discussed earlier. The \tty{return} value is always of type \cint, being
zero (false) if the value is not a member of the relevant calss,
or non-zero (true) if it is.
\newpage
Some examples are as follows:
\begin{description}
\item \tty{int isalpha(int c)} : Letter (i.e.\ ~"alphabetic"~)?
\item \tty{int isdigit(int c)} : Digit?
\item \tty{int isalnum(int c)} : Letter or digit
(~"alphanumeric)?
\item \tty{int islower(int c)} : Lower case letter?
\item \tty{int isupper(int c)} : Upper case letter?
\item \tty{int isspace(int c)} : ~"Whitespace"~ (i.e.\ space,
newline, tab, etc.)?
\item \tty{int isprint(int c)} : Printable or displayable
(including space)?
\end{description}

\tty{ctype.h} also provides two functions which convert the case
of letters:
\begin{description}
\item \tty{int tolower(int c)}
\item \tty{int toupper(int c)}
\end{description}

\section{String Functions: \tty{string.h}}

\tty{string.h} provides prototypes for a wide range of functions
which operate upon strings in various ways. A brief description
of a small sample of these follows. Note that where one of these
functions potentially modifies a string, it {\it might}, in
general, make it {\it longer\/}; therefore in passing in a
pointer to the string which will be modified, you must make sure
that the \cchar\ array holding this string is big enough to hold
the longest possible string (including the nul terminator) which
might conceivably result from the string operation(s). If you
fail to watch out for this the results will generally be
unpredictable~-~and definitely not very pleasant.

\subsection*{\tty{char *strcpy(char *s, char *t)}}

Copy the string pointed to by \tty{t} to that pointed to by
\tty{s}. The \tty{return} value is simply \tty{s} (i.e.\ a pointer to
the destination string); this is sometimes
convenient in forming more complex expressions, but, more
usually, it can be ignored (discarded).

\subsection*{\tty{char *strcat(char *s, char *t)}}

Concatenate the strings pointed at by \tty{s} and \tty{t}; the
result is pointed to by \tty{s}.  That is, in effect, the
characters from string \tty{t} are added on at the end of string
\tty{s}. The \tty{return} value is again simply \tty{s}.

\subsection*{\tty{int strcmp(char *s, char *t)}}

Compare the strings pointed to by \tty{s} and \tty{t}.  The
\tty{return} value is zero if the two strings are identical; it
is negative if \tty{s} would come before \tty{t} in an
alphabetical ordering; and positive if \tty{t} would come before
\tty{s}.

\section{Conclusion}

This essay serves only to skim the surface of the facilities
offered by the \C\ Standard Library. It is well worth your while
to become reasonably familiar with the full range of services
which are available in the library: it can speed up programming
of many applications very considerably.

\end{document}
