Category : C Source Code
Archive   : ANSI-C.ZIP
Filename : LIB

 
Output of file : LIB contained in archive : ANSI-C.ZIP


4. LIBRARY


4.1 INTRODUCTION


4.1.1 Definitions of terms

A string is a contiguous sequence of characters terminated by and
including the first null character. It is represented by a pointer to its
initial (lowest addressed) character and its length is the number of
characters preceding the null character.
A letter is a printing character in the execution character set
corresponding to any of the 52 required lower-case and upper-case letters in
the source character set, listed in $2.2.1.
The decimal-point character is the character used by functions that
convert floating-point numbers to or from character sequences to denote the
beginning of the fractional part of such character sequences./80/ It is
represented in the text and examples by a period, but may be changed by the
setlocale function.

Forward references: character handling ($4.3), the setlocale function
($4.4.1.1).

4.1.2 Standard headers

Each library function is declared in a header ,/81/ whose contents are
made available by the #include preprocessing directive. The header declares
a set of related functions, plus any necessary types and additional macros
needed to facilitate their use. Each header declares and defines only those
identifiers listed in its associated section. All external identifiers
declared in any of the headers are reserved, whether or not the associated
header is included. All external identifiers that begin with an underscore
are reserved. All other identifiers that begin with an underscore and
either an upper-case letter or another underscore are reserved. If the
program defines an external identifier with the same name as a reserved
external identifier, even in a semantically equivalent form, the behavior is
undefined./82/
The standard headers are








If a file with the same name as one of the above < and > delimited
sequences, not provided as part of the implementation, is placed in any of
the standard places for a source file to be included, the behavior is
undefined.
Headers may be included in any order; each may be included more than once
in a given scope, with no effect different from being included only once,
except that the effect of including depends on the definition of
NDEBUG . If used, a header shall be included outside of any external
declaration or definition, and it shall first be included before the first
reference to any of the functions or objects it declares, or to any of the
types or macros it defines. Furthermore, the program shall not have any
macros with names lexically identical to keywords currently defined prior to
the inclusion.

Forward references: diagnostics ($4.2).

4.1.3 Errors

The header defines several macros, all relating to the
reporting of error conditions.
The macros are

EDOM
ERANGE

which expand to distinct nonzero integral constant expressions; and

errno

which expands to a modifiable lvalue/83/ that has type int , the value of
which is set to a positive error number by several library functions. It is
unspecified whether errno is a macro or an identifier declared with external
linkage. If a macro definition is suppressed in order to access an actual
object, or a program defines an external identifier with the name errno ,
the behavior is undefined.
The value of errno is zero at program startup, but is never set to zero
by any library function./84/ The value of errno may be set to nonzero by
a library function call whether or not there is an error, provided the use
of errno is not documented in the description of the function in the
Standard.
Additional macro definitions, beginning with E and a digit or E and an
upper-case letter,/85/ may also be specified by the implementation.

4.1.4 Limits and

The headers and define several macros that expand to
various limits and parameters.
The macros, their meanings, and their minimum magnitudes are listed in
$2.2.4.2.

4.1.5 Common definitions

The following types and macros are defined in the standard header
. Some are also defined in other headers, as noted in their
respective sections.
The types are

ptrdiff_t

which is the signed integral type of the result of subtracting two pointers;


size_t

which is the unsigned integral type of the result of the sizeof operator;
and

wchar_t

which is an integral type whose range of values can represent distinct codes
for all members of the largest extended character set specified among the
supported locales; the null character shall have the code value zero and
each member of the basic character set defined in $2.2.1 shall have a code
value equal to its value when used as the lone character in an integer
character constant.

The macros are

NULL

which expands to an implementation-defined null pointer constant; and

offsetof( type, member-designator)

which expands to an integral constant expression that has type size_t , the
value of which is the offset in bytes, to the structure member (designated
by member-designator ), from the beginning of its structure (designated by
type ). The member-designator shall be such that given

static type t;

then the expression &(t. member-designator ) evaluates to an address
constant. (If the specified member is a bit-field, the behavior is
undefined.)

Forward references: localization ($4.4).


4.1.6 Use of library functions

Each of the following statements applies unless explicitly stated
otherwise in the detailed descriptions that follow. If an argument to a
function has an invalid value (such as a value outside the domain of the
function, or a pointer outside the address space of the program, or a null
pointer), the behavior is undefined. Any function declared in a header may
be implemented as a macro defined in the header, so a library function
should not be declared explicitly if its header is included. Any macro
definition of a function can be suppressed locally by enclosing the name of
the function in parentheses, because the name is then not followed by the
left parenthesis that indicates expansion of a macro function name. For the
same syntactic reason, it is permitted to take the address of a library
function even if it is also defined as a macro./86/ The use of #undef to
remove any macro definition will also ensure that an actual function is
referred to. Any invocation of a library function that is implemented as a
macro will expand to code that evaluates each of its arguments exactly once,
fully protected by parentheses where necessary, so it is generally safe to
use arbitrary expressions as arguments. Likewise, those function-like
macros described in the following sections may be invoked in an expression
anywhere a function with a compatible return type could be called./87/
Provided that a library function can be declared without reference to any
type defined in a header, it is also permissible to declare the function,
either explicitly or implicitly, and use it without including its associated
header. If a function that accepts a variable number of arguments is not
declared (explicitly or by including its associated header), the behavior is
undefined.

Examples

The function atoi may be used in any of several ways:

* by use of its associated header (possibly generating a macro expansion)

#include
const char *str;
/*...*/
i = atoi(str);



* by use of its associated header (assuredly generating a true function
reference)

#include
#undef atoi
const char *str;
/*...*/
i = atoi(str);

or

#include
const char *str;

/*...*/
i = (atoi)(str);



* by explicit declaration

extern int atoi(const char *);
const char *str;
/*...*/
i = atoi(str);



* by implicit declaration

const char *str;
/*...*/
i = atoi(str);



4.2 DIAGNOSTICS

The header defines the assert macro and refers to another
macro,

NDEBUG

which is not defined by . If NDEBUG is defined as a macro name
at the point in the source file where is included, the assert
macro is defined simply as

#define assert(ignore) ((void)0)


The assert macro shall be implemented as a macro, not as an actual
function. If the macro definition is suppressed in order to access an
actual function, the behavior is undefined.

4.2.1 Program diagnostics


4.2.1.1 The assert macro


Synopsis


#include
void assert(int expression);



Description

The assert macro puts diagnostics into programs. When it is executed, if
expression is false (that is, compares equal to 0), the assert macro writes
information about the particular call that failed (including the text of the
argument, the name of the source file, and the source line number EM the
latter are respectively the values of the preprocessing macros __FILE__ and
__LINE__ ) on the standard error file in an implementation-defined
format./88/
expression , xyz , nnn It then calls the abort function.

Returns


The assert macro returns no value.

Forward references: the abort function ($4.10.4.1).

4.3 CHARACTER HANDLING

The header declares several functions useful for testing and
mapping characters./89/ In all cases the argument is an int , the value
of which shall be representable as an unsigned char or shall equal the value
of the macro EOF . If the argument has any other value, the behavior is
undefined.
The behavior of these functions is affected by the current locale. Those
functions that have no implementation-defined aspects in the C locale are
noted below.
The term printing character refers to a member of an
implementation-defined set of characters, each of which occupies one
printing position on a display device; the term control character refers to
a member of an implementation-defined set of characters that are not
printing characters./90/

Forward references: EOF ($4.9.1), localization ($4.4).

4.3.1 Character testing functions

The functions in this section return nonzero (true) if and only if the
value of the argument c conforms to that in the description of the function.


4.3.1.1 The isalnum function


Synopsis


#include
int isalnum(int c);



Description

The isalnum function tests for any character for which isalpha or isdigit
is true.

4.3.1.2 The isalpha function


Synopsis


#include
int isalpha(int c);



Description

The isalpha function tests for any character for which isupper or islower
is true, or any of an implementation-defined set of characters for which
none of iscntrl , isdigit , ispunct , or isspace is true. In the C locale,
isalpha returns true only for the characters for which isupper or islower is
true.

4.3.1.3 The iscntrl function


Synopsis


#include
int iscntrl(int c);



Description

The iscntrl function tests for any control character.

4.3.1.4 The isdigit function


Synopsis


#include
int isdigit(int c);



Description

The isdigit function tests for any decimal-digit character (as defined in
$2.2.1).

4.3.1.5 The isgraph function


Synopsis


#include
int isgraph(int c);



Description

The isgraph function tests for any printing character except space (' ').


4.3.1.6 The islower function


Synopsis


#include
int islower(int c);



Description

The islower function tests for any lower-case letter or any of an
implementation-defined set of characters for which none of iscntrl , isdigit
, ispunct , or isspace is true. In the C locale, islower returns true only
for the characters defined as lower-case letters (as defined in $2.2.1).

4.3.1.7 The isprint function


Synopsis


#include
int isprint(int c);



Description

The isprint function tests for any printing character including space ('
').

4.3.1.8 The ispunct function


Synopsis


#include
int ispunct(int c);



Description

The ispunct function tests for any printing character except space (' ')
or a character for which isalnum is true.

4.3.1.9 The isspace function


Synopsis


#include
int isspace(int c);



Description

The isspace function tests for the standard white-space characters or for
any of an implementation-defined set of characters for which isalnum is
false. The standard white-space characters are the following: space (' '),
form feed ('\f'), new-line ('\n'), carriage return ('\r'), horizontal tab
('\t'), and vertical tab ('\v'). In the C locale, isspace returns true only
for the standard white-space characters.

4.3.1.10 The isupper function


Synopsis


#include
int isupper(int c);



Description

The isupper function tests for any upper-case letter or any of an
implementation-defined set of characters for which none of iscntrl , isdigit
, ispunct , or isspace is true. In the C locale, isupper returns true only
for the characters defined as upper-case letters (as defined in $2.2.1).


4.3.1.11 The isxdigit function


Synopsis


#include
int isxdigit(int c);



Description

The isxdigit function tests for any hexadecimal-digit character (as
defined in $3.1.3.2).

4.3.2 Character case mapping functions


4.3.2.1 The tolower function


Synopsis


#include
int tolower(int c);



Description

The tolower function converts an upper-case letter to the corresponding
lower-case letter.

Returns

If the argument is an upper-case letter, the tolower function returns the
corresponding lower-case letter if there is one; otherwise the argument is
returned unchanged. In the C locale, tolower maps only the characters for
which isupper is true to the corresponding characters for which islower is
true.

4.3.2.2 The toupper function


Synopsis


#include
int toupper(int c);



Description

The toupper function converts a lower-case letter to the corresponding
upper-case letter.

Returns

If the argument is a lower-case letter, the toupper function returns the
corresponding upper-case letter if there is one; otherwise the argument is
returned unchanged. In the C locale, toupper maps only the characters for
which islower is true to the corresponding characters for which isupper is

true.

4.4 LOCALIZATION

The header declares two functions, one type, and defines
several macros.
The type is

struct lconv

which contains members related to the formatting of numeric values. The
structure shall contain at least the following members, in any order. The
semantics of the members and their normal ranges is explained in $4.4.2.1.
In the C locale, the members shall have the values specified in the
comments.

char *decimal_point; /* "." */
char *thousands_sep; /* "" */
char *grouping; /* "" */
char *int_curr_symbol; /* "" */
char *currency_symbol; /* "" */
char *mon_decimal_point; /* "" */
char *mon_thousands_sep; /* "" */
char *mon_grouping; /* "" */
char *positive_sign; /* "" */
char *negative_sign; /* "" */
char int_frac_digits; /* CHAR_MAX */
char frac_digits; /* CHAR_MAX */
char p_cs_precedes; /* CHAR_MAX */
char p_sep_by_space; /* CHAR_MAX */
char n_cs_precedes; /* CHAR_MAX */
char n_sep_by_space; /* CHAR_MAX */
char p_sign_posn; /* CHAR_MAX */
char n_sign_posn; /* CHAR_MAX */


The macros defined are NULL (described in $4.1.5); and

LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME

which expand to distinct integral constant expressions, suitable for use as
the first argument to the setlocale function. Additional macro definitions,
beginning with the characters LC_ and an upper-case letter,/91/ may also be
specified by the implementation.

4.4.1 Locale control


4.4.1.1 The setlocale function


Synopsis


#include
char *setlocale(int category, const char *locale);

Description

The setlocale function selects the appropriate portion of the program's
locale as specified by the category and locale arguments. The setlocale
function may be used to change or query the program's entire current locale
or portions thereof. The value LC_ALL for category names the program's
entire locale; the other values for category name only a portion of the
program's locale. LC_COLLATE affects the behavior of the strcoll and
strxfrm functions. LC_CTYPE affects the behavior of the character handling
functions/92/ and the multibyte functions. LC_MONETARY affects the monetary
formatting information returned by the localeconv function. LC_NUMERIC
affects the decimal-point character for the formatted input/output functions
and the string conversion functions, as well as the non-monetary formatting
information returned by the localeconv function. LC_TIME affects the
behavior of the strftime function.
A value of C for locale specifies the minimal environment for C
translation; a value of for locale specifies the implementation-defined
native environment. Other implementation-defined strings may be passed as
the second argument to setlocale .
At program startup, the equivalent of

setlocale(LC_ALL, "C");

is executed.
The implementation shall behave as if no library function calls the
setlocale function.

Returns

If a pointer to a string is given for locale and the selection can be
honored, the setlocale function returns the string associated with the
specified category for the new locale. If the selection cannot be honored,
the setlocale function returns a null pointer and the program's locale is
not changed.
A null pointer for locale causes the setlocale function to return the
string associated with the category for the program's current locale; the
program's locale is not changed.
The string returned by the setlocale function is such that a subsequent
call with that string and its associated category will restore that part of
the program's locale. The string returned shall not be modified by the
program, but may be overwritten by a subsequent call to the setlocale
function.

Forward references: formatted input/output functions ($4.9.6), the multibyte
character functions ($4.10.7), the multibyte string functions ($4.10.8),
string conversion functions ($4.10.1), the strcoll function ($4.11.4.3), the
strftime function ($4.12.3.5), the strxfrm function ($4.11.4.5).

4.4.2 Numeric formatting convention inquiry


4.4.2.1 The localeconv function


Synopsis


#include
struct lconv *localeconv(void);



Description

The localeconv function sets the components of an object with type struct
lconv with values appropriate for the formatting of numeric quantities
(monetary and otherwise) according to the rules of the current locale.
The members of the structure with type char * are strings, any of which

(except decimal_point ) can point to , to indicate that the value is not
available in the current locale or is of zero length. The members with type
char are nonnegative numbers, any of which can be CHAR_MAX to indicate that
the value is not available in the current locale. The members include the
following:
The decimal-point character used to format non-monetary quantities.
The character used to separate groups of digits to the left of the
decimal-point character in formatted non-monetary quantities.
A string whose elements indicate the size of each group of digits in
formatted non-monetary quantities.
The international currency symbol applicable to the current locale. The
first three characters contain the alphabetic international currency symbol
in accordance with those specified in ISO 4217 Codes for the Representation
of Currency and Funds .The fourth character (immediately preceding the null
character) is the character used to separate the international currency
symbol from the monetary quantity.
The local currency symbol applicable to the current locale.
The decimal-point used to format monetary quantities.
The separator for groups of digits to the left of the decimal-point in
formatted monetary quantities.
A string whose elements indicate the size of each group of digits in
formatted monetary quantities.
The string used to indicate a nonnegative-valued formatted monetary
quantity.
The string used to indicate a negative-valued formatted monetary quantity.
The number of fractional digits (those to the right of the decimal-point) to
be displayed in a internationally formatted monetary quantity.
The number of fractional digits (those to the right of the decimal-point) to
be displayed in a formatted monetary quantity.
Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the
value for a nonnegative formatted monetary quantity.
Set to 1 or 0 if the currency_symbol respectively is or is not separated by
a space from the value for a nonnegative formatted monetary quantity.
Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the
value for a negative formatted monetary quantity.
Set to 1 or 0 if the currency_symbol respectively is or is not separated by
a space from the value for a negative formatted monetary quantity.
Set to a value indicating the positioning of the positive_sign for a
nonnegative formatted monetary quantity.
Set to a value indicating the positioning of the negative_sign for a
negative formatted monetary quantity.
The elements of grouping and mon_grouping are interpreted according to
the following: No further grouping is to be performed. The previous element
is to be repeatedly used for the remainder of the digits. The value is the
number of digits that comprise the current group. The next element is
examined to determine the size of the next group of digits to the left of
the current group.
The value of p_sign_posn and n_sign_posn is interpreted according to the
following: Parentheses surround the quantity and currency_symbol . The sign
string precedes the quantity and currency_symbol . The sign string succeeds
the quantity and currency_symbol . The sign string immediately precedes the
currency_symbol . The sign string immediately succeeds the currency_symbol
.
The implementation shall behave as if no library function calls the
localeconv function.

Returns

The localeconv function returns a pointer to the filled-in object. The
structure pointed to by the return value shall not be modified by the
program, but may be overwritten by a subsequent call to the localeconv
function. In addition, calls to the setlocale function with categories
LC_ALL , LC_MONETARY , or LC_NUMERIC may overwrite the contents of the
structure.

Examples


The following table illustrates the rules used by four countries to
format monetary quantities.

Country Positive format Negative format International format

Italy L.1.234 -L.1.234 ITL.1.234
Netherlands F 1.234,56 F -1.234,56 NLG 1.234,56
Norway kr1.234,56 kr1.234,56- NOK 1.234,56
Switzerland SFrs.1,234.56 SFrs.1,234.56C CHF 1,234.56


For these four countries, the respective values for the monetary members
of the structure returned by localeconv are:

Italy Netherlands Norway Switzerland

int_curr_symbol "ITL." "NLG " "NOK " "CHF "
currency_symbol "L." "F" "kr" "SFrs."
mon_decimal_point "" "," "," "."
mon_thousands_sep "." "." "." ","
mon_grouping "\3" "\3" "\3" "\3"
positive_sign "" "" "" ""
negative_sign "-" "-" "-" "C"
int_frac_digits 0 2 2 2
frac_digits 0 2 2 2
p_cs_precedes 1 1 1 1
p_sep_by_space 0 1 0 0
n_cs_precedes 1 1 1 1
n_sep_by_space 0 1 0 0
p_sign_posn 1 1 1 1
n_sign_posn 1 4 2 2



4.5 MATHEMATICS

The header declares several mathematical functions and defines
one macro. The functions take double-precision arguments and return
double-precision values./93/ Integer arithmetic functions and conversion
functions are discussed later.
The macro defined is

HUGE_VAL

which expands to a positive double expression, not necessarily representable
as a float .

Forward references: integer arithmetic functions ($4.10.6), the atof
function ($4.10.1.1), the strtod function ($4.10.1.4).

4.5.1 Treatment of error conditions

The behavior of each of these functions is defined for all representable
values of its input arguments. Each function shall execute as if it were a
single operation, without generating any externally visible exceptions.
For all functions, a domain error occurs if an input argument is outside
the domain over which the mathematical function is defined. The description
of each function lists any required domain errors; an implementation may
define additional domain errors, provided that such errors are consistent
with the mathematical definition of the function./94/ On a domain error,
the function returns an implementation-defined value; the value of the macro
EDOM is stored in errno .
Similarly, a range error occurs if the result of the function cannot be
represented as a double value. If the result overflows (the magnitude of
the result is so large that it cannot be represented in an object of the

specified type), the function returns the value of the macro HUGE_VAL , with
the same sign as the correct value of the function; the value of the macro
ERANGE is stored in errno . If the result underflows (the magnitude of the
result is so small that it cannot be represented in an object of the
specified type), the function returns zero; whether the integer expression
errno acquires the value of the macro ERANGE is implementation-defined.

4.5.2 Trigonometric functions


4.5.2.1 The acos function


Synopsis


#include
double acos(double x);



Description

The acos function computes the principal value of the arc cosine of x .
A domain error occurs for arguments not in the range [-1, +1].

Returns

The acos function returns the arc cosine in the range [0, PI] radians.

4.5.2.2 The asin function


Synopsis


#include
double asin(double x);



Description

The asin function computes the principal value of the arc sine of x . A
domain error occurs for arguments not in the range [-1, +1].

Returns

The asin function returns the arc sine in the range [-PI/2, +PI/2]
radians.

4.5.2.3 The atan function


Synopsis


#include
double atan(double x);



Description

The atan function computes the principal value of the arc tangent of x .


Returns

The atan function returns the arc tangent in the range [-PI/2, +PI/2]
radians.

4.5.2.4 The atan2 function


Synopsis


#include
double atan2(double y, double x);



Description

The atan2 function computes the principal value of the arc tangent of y/x
, using the signs of both arguments to determine the quadrant of the return
value. A domain error may occur if both arguments are zero.

Returns

The atan2 function returns the arc tangent of y/x , in the range [-PI,
+PI] radians.

4.5.2.5 The cos function


Synopsis


#include
double cos(double x);



Description

The cos function computes the cosine of x (measured in radians). A large
magnitude argument may yield a result with little or no significance.

Returns

The cos function returns the cosine value.

4.5.2.6 The sin function


Synopsis


#include
double sin(double x);



Description

The sin function computes the sine of x (measured in radians). A large
magnitude argument may yield a result with little or no significance.

Returns

The sin function returns the sine value.

4.5.2.7 The tan function


Synopsis


#include
double tan(double x);



Description

The tan function returns the tangent of x (measured in radians). A large
magnitude argument may yield a result with little or no significance.

Returns

The tan function returns the tangent value.

4.5.3 Hyperbolic functions


4.5.3.1 The cosh function


Synopsis


#include
double cosh(double x);



Description

The cosh function computes the hyperbolic cosine of x . A range error
occurs if the magnitude of x is too large.

Returns

The cosh function returns the hyperbolic cosine value.

4.5.3.2 The sinh function


Synopsis


#include
double sinh(double x);



Description

The sinh function computes the hyperbolic sine of x . A range error
occurs if the magnitude of x is too large.

Returns

The sinh function returns the hyperbolic sine value.

4.5.3.3 The tanh function



Synopsis


#include
double tanh(double x);



Description

The tanh function computes the hyperbolic tangent of x .

Returns

The tanh function returns the hyperbolic tangent value.

4.5.4 Exponential and logarithmic functions


4.5.4.1 The exp function


Synopsis


#include
double exp(double x);



Description

The exp function computes the exponential function of x . A range error
occurs if the magnitude of x is too large.

Returns

The exp function returns the exponential value.

4.5.4.2 The frexp function


Synopsis


#include
double frexp(double value, int *exp);



Description

The frexp function breaks a floating-point number into a normalized
fraction and an integral power of 2. It stores the integer in the int
object pointed to by exp .

Returns

The frexp function returns the value x , such that x is a double with
magnitude in the interval [1/2, 1) or zero, and value equals x times 2
raised to the power *exp . If value is zero, both parts of the result are
zero.

4.5.4.3 The ldexp function



Synopsis


#include
double ldexp(double x, int exp);



Description

The ldexp function multiplies a floating-point number by an integral
power of 2. A range error may occur.

Returns

The ldexp function returns the value of x times 2 raised to the power exp
.

4.5.4.4 The log function


Synopsis


#include
double log(double x);



Description

The log function computes the natural logarithm of x. A domain error
occurs if the argument is negative. A range error occurs if the argument is
zero and the logarithm of zero cannot be represented.

Returns

The log function returns the natural logarithm.

4.5.4.5 The log10 function


Synopsis


#include
double log10(double x);



Description

The log10 function computes the base-ten logarithm of x . A domain error
occurs if the argument is negative. A range error occurs if the argument is
zero and the logarithm of zero cannot be represented.

Returns

The log10 function returns the base-ten logarithm.

4.5.4.6 The modf function


Synopsis



#include
double modf(double value, double *iptr);



Description

The modf function breaks the argument value into integral and fractional
parts, each of which has the same sign as the argument. It stores the
integral part as a double in the object pointed to by iptr .

Returns

The modf function returns the signed fractional part of value .

4.5.5 Power functions


4.5.5.1 The pow function


Synopsis


#include
double pow(double x, double y);



Description

The pow function computes x raised to the power y . A domain error
occurs if x is negative and y is not an integer. A domain error occurs if
the result cannot be represented when x is zero and y is less than or equal
to zero. A range error may occur.

Returns

The pow function returns the value of x raised to the power y .

4.5.5.2 The sqrt function


Synopsis


#include
double sqrt(double x);



Description

The sqrt function computes the nonnegative square root of x . A domain
error occurs if the argument is negative.

Returns

The sqrt function returns the value of the square root.

4.5.6 Nearest integer, absolute value, and remainder functions


4.5.6.1 The ceil function




Synopsis


#include
double ceil(double x);



Description

The ceil function computes the smallest integral value not less than x .


Returns

The ceil function returns the smallest integral value not less than x ,
expressed as a double.

4.5.6.2 The fabs function


Synopsis


#include
double fabs(double x);



Description

The fabs function computes the absolute value of a floating-point number
x .

Returns

The fabs function returns the absolute value of x.

4.5.6.3 The floor function


Synopsis


#include
double floor(double x);



Description

The floor function computes the largest integral value not greater than x
.

Returns

The floor function returns the largest integral value not greater than x
, expressed as a double.

4.5.6.4 The fmod function


Synopsis


#include
double fmod(double x, double y);



Description

The fmod function computes the floating-point remainder of x/y .

Returns

The fmod function returns the value x i y , for some integer i such that,
if y is nonzero, the result has the same sign as x and magnitude less than
the magnitude of y . If y is zero, whether a domain error occurs or the
fmod function returns zero is implementation-defined.

4.6 NON-LOCAL JUMPS

The header defines the macro setjmp , and declares one
function and one type, for bypassing the normal function call and return
discipline./95/
The type declared is

jmp_buf

which is an array type suitable for holding the information needed to
restore a calling environment.
It is unspecified whether setjmp is a macro or an identifier declared
with external linkage. If a macro definition is suppressed in order to
access an actual function, or a program defines an external identifier with
the name setjmp , the behavior is undefined.

4.6.1 Save calling environment


4.6.1.1 The setjmp macro


Synopsis


#include
int setjmp(jmp_buf env);



Description

The setjmp macro saves its calling environment in its jmp_buf argument
for later use by the longjmp function.

Returns

If the return is from a direct invocation, the setjmp macro returns the
value zero. If the return is from a call to the longjmp function, the
setjmp macro returns a nonzero value.

"Environmental constraint"

An invocation of the setjmp macro shall appear only in one of the
following contexts:

* the entire controlling expression of a selection or iteration statement;

* one operand of a relational or equality operator with the other operand

an integral constant expression, with the resulting expression being the
entire controlling expression of a selection or iteration statement;

* the operand of a unary ! operator with the resulting expression being the
entire controlling expression of a selection or iteration statement; or

* the entire expression of an expression statement (possibly cast to void
).

4.6.2 Restore calling environment


4.6.2.1 The longjmp function


Synopsis


#include
void longjmp(jmp_buf env, int val);



Description

The longjmp function restores the environment saved by the most recent
invocation of the setjmp macro in the same invocation of the program, with
the corresponding jmp_buf argument. If there has been no such invocation,
or if the function containing the invocation of the setjmp macro has
terminated execution/96/ in the interim, the behavior is undefined.
All accessible objects have values as of the time longjmp was called,
except that the values of objects of automatic storage duration that do not
have volatile type and have been changed between the setjmp invocation and
longjmp call are indeterminate.
As it bypasses the usual function call and return mechanisms, the longjmp
function shall execute correctly in contexts of interrupts, signals and any
of their associated functions. However, if the longjmp function is invoked
from a nested signal handler (that is, from a function invoked as a result
of a signal raised during the handling of another signal), the behavior is
undefined.

Returns

After longjmp is completed, program execution continues as if the
corresponding invocation of the setjmp macro had just returned the value
specified by val . The longjmp function cannot cause the setjmp macro to
return the value 0; if val is 0, the setjmp macro returns the value 1.

4.7 SIGNAL HANDLING

The header declares a type and two functions and defines
several macros, for handling various signals (conditions that may be
reported during program execution).
The type defined is

sig_atomic_t

which is the integral type of an object that can be accessed as an atomic
entity, even in the presence of asynchronous interrupts.
The macros defined are

SIG_DFL
SIG_ERR
SIG_IGN

which expand to distinct constant expressions that have type compatible with

the second argument to and the return value of the signal function, and
whose value compares unequal to the address of any declarable function; and
the following, each of which expands to a positive integral constant
expression that is the signal number corresponding to the specified
condition: abnormal termination, such as is initiated by the abort function
an erroneous arithmetic operation, such as zero divide or an operation
resulting in overflow detection of an invalid function image, such as an
illegal instruction receipt of an interactive attention signal an invalid
access to storage a termination request sent to the program
An implementation need not generate any of these signals, except as a
result of explicit calls to the raise function. Additional signals and
pointers to undeclarable functions, with macro definitions beginning,
respectively, with the letters SIG and an upper-case letter or with SIG_ and
an upper-case letter,/97/ may also be specified by the implementation. The
complete set of signals, their semantics, and their default handling is
implementation-defined; all signal values shall be positive.

4.7.1 Specify signal handling


4.7.1.1 The signal function


Synopsis


#include
void (*signal(int sig, void (*func)(int)))(int);



Description

The signal function chooses one of three ways in which receipt of the
signal number sig is to be subsequently handled. If the value of func is
SIG_DFL , default handling for that signal will occur. If the value of
func is SIG_IGN , the signal will be ignored. Otherwise, func shall point
to a function to be called when that signal occurs. Such a function is
called a signal handler .
When a signal occurs, if func points to a function, first the equivalent
of signal(sig, SIG_DFL); is executed or an implementation-defined blocking
of the signal is performed. (If the value of sig is SIGILL, whether the
reset to SIG_DFL occurs is implementation-defined.) Next the equivalent of
(*func)(sig); is executed. The function func may terminate by executing a
return statement or by calling the abort , exit , or longjmp function. If
func executes a return statement and the value of sig was SIGFPE or any
other implementation-defined value corresponding to a computational
exception, the behavior is undefined. Otherwise, the program will resume
execution at the point it was interrupted.
If the signal occurs other than as the result of calling the abort or
raise function, the behavior is undefined if the signal handler calls any
function in the standard library other than the signal function itself or
refers to any object with static storage duration other than by assigning a
value to a static storage duration variable of type volatile sig_atomic_t .
Furthermore, if such a call to the signal function results in a SIG_ERR
return, the value of errno is indeterminate.
At program startup, the equivalent of

signal(sig, SIG_IGN);

may be executed for some signals selected in an implementation-defined
manner; the equivalent of

signal(sig, SIG_DFL);

is executed for all other signals defined by the implementation.

The implementation shall behave as if no library function calls the
signal function.

Returns

If the request can be honored, the signal function returns the value of
func for the most recent call to signal for the specified signal sig .
Otherwise, a value of SIG_ERR is returned and a positive value is stored in
errno .

Forward references: the abort function ($4.10.4.1).

4.7.2 Send signal


4.7.2.1 The raise function


Synopsis


#include
int raise(int sig);



Description

The raise function sends the signal sig to the executing program.

Returns

The raise function returns zero if successful, nonzero if unsuccessful.

4.8 VARIABLE ARGUMENTS

The header declares a type and defines three macros, for
advancing through a list of arguments whose number and types are not known
to the called function when it is translated.
A function may be called with a variable number of arguments of varying
types. As described in $3.7.1, its parameter list contains one or more
parameters. The rightmost parameter plays a special role in the access
mechanism, and will be designated parmN in this description.
The type declared is

va_list

which is a type suitable for holding information needed by the macros
va_start , va_arg , and va_end . If access to the varying arguments is
desired, the called function shall declare an object (referred to as ap
in this section) having type va_list . The object ap may be passed as an
argument to another function; if that function invokes the va_arg macro with
parameter ap , the value of ap in the calling function is indeterminate and
shall be passed to the va_end macro prior to any further reference to ap .

4.8.1 Variable argument list access macros

The va_start and va_arg macros described in this section shall be
implemented as macros, not as actual functions. It is unspecified whether
va_end is a macro or an identifier declared with external linkage. If a
macro definition is suppressed in order to access an actual function, or a
program defines an external identifier with the name va_end , the behavior
is undefined. The va_start and va_end macros shall be invoked in the
function accepting a varying number of arguments, if access to the varying
arguments is desired.

4.8.1.1 The va_start macro


Synopsis


#include
void va_start(va_list ap, parmN);



Description

The va_start macro shall be invoked before any access to the unnamed
arguments.
The va_start macro initializes ap for subsequent use by va_arg and
va_end .
The parameter parmN is the identifier of the rightmost parameter in the
variable parameter list in the function definition (the one just before the
, ... ). If the parameter parmN is declared with the register storage
class, with a function or array type, or with a type that is not compatible
with the type that results after application of the default argument
promotions, the behavior is undefined.

Returns

The va_start macro returns no value.

4.8.1.2 The va_arg macro


Synopsis


#include
type va_arg(va_list ap, type);



Description

The va_arg macro expands to an expression that has the type and value of
the next argument in the call. The parameter ap shall be the same as the
va_list ap initialized by va_start . Each invocation of va_arg modifies ap
so that the values of successive arguments are returned in turn. The
parameter type is a type name specified such that the type of a pointer to
an object that has the specified type can be obtained simply by postfixing a
* to type . If there is no actual next argument, or if type is not
compatible with the type of the actual next argument (as promoted according
to the default argument promotions), the behavior is undefined.

Returns

The first invocation of the va_arg macro after that of the va_start macro
returns the value of the argument after that specified by parmN . Successive
invocations return the values of the remaining arguments in succession.

4.8.1.3 The va_end macro


Synopsis


#include
void va_end(va_list ap);



Description

The va_end macro facilitates a normal return from the function whose
variable argument list was referred to by the expansion of va_start that
initialized the va_list ap . The va_end macro may modify ap so that it is
no longer usable (without an intervening invocation of va_start ). If there
is no corresponding invocation of the va_start macro, or if the va_end macro
is not invoked before the return, the behavior is undefined.

Returns

The va_end macro returns no value.

Example

The function f1 gathers into an array a list of arguments that are
pointers to strings (but not more than MAXARGS arguments), then passes the
array as a single argument to function f2 . The number of pointers is
specified by the first argument to f1 .

#include
#define MAXARGS 31

void f1(int n_ptrs, ...)
{
va_list ap;
char *array[MAXARGS];
int ptr_no = 0;

if (n_ptrs > MAXARGS)
n_ptrs = MAXARGS;
va_start(ap, n_ptrs);
while (ptr_no < n_ptrs)
array[ptr_no++] = va_arg(ap, char *);
va_end(ap);
f2(n_ptrs, array);
}

Each call to f1 shall have visible the definition of the function or a
declaration such as

void f1(int, ...);



4.9 INPUT/OUTPUT


4.9.1 Introduction

The header declares three types, several macros, and many
functions for performing input and output.
The types declared are size_t (described in $4.1.5);

FILE

which is an object type capable of recording all the information needed to
control a stream, including its file position indicator, a pointer to its
associated buffer, an error indicator that records whether a read/write
error has occurred, and an end-of-file indicator that records whether the
end of the file has been reached; and

fpos_t

which is an object type capable of recording all the information needed to
specify uniquely every position within a file.
The macros are NULL (described in $4.1.5);

_IOFBF
_IOLBF
_IONBF

which expand to distinct integral constant expressions, suitable for use as
the third argument to the setvbuf function;

BUFSIZ

which expands to an integral constant expression, which is the size of the
buffer used by the setbuf function;

EOF

which expands to a negative integral constant expression that is returned by
several functions to indicate end-of-file ,that is, no more input from a
stream;

FOPEN_MAX

which expands to an integral constant expression that is the minimum number
of files that the implementation guarantees can be open simultaneously;

FILENAME_MAX

which expands to an integral constant expression that is the maximum length
for a file name string that the implementation guarantees can be opened;/98/


L_tmpnam

which expands to an integral constant expression that is the size of an
array of char large enough to hold a temporary file name string generated by
the tmpnam function;

SEEK_CUR
SEEK_END
SEEK_SET

which expand to distinct integral constant expressions, suitable for use as
the third argument to the fseek function;

TMP_MAX

which expands to an integral constant expression that is the minimum number
of unique file names that shall be generated by the tmpnam function;

stderr
stdin
stdout

which are expressions of type ``pointer to FILE '' that point to the FILE
objects associated, respectively, with the standard error, input, and output
streams.

Forward references: files ($4.9.3), the fseek function ($4.9.9.2), streams
($4.9.2), the tmpnam function ($4.9.4.4).

4.9.2 Streams

Input and output, whether to or from physical devices such as terminals
and tape drives, or whether to or from files supported on structured storage

devices, are mapped into logical data streams ,whose properties are more
uniform than their various inputs and outputs. Two forms of mapping are
supported, for text streams and for binary streams ./99/
A text stream is an ordered sequence of characters composed into lines ,
each line consisting of zero or more characters plus a terminating new-line
character. Whether the last line requires a terminating new-line character
is implementation-defined. Characters may have to be added, altered, or
deleted on input and output to conform to differing conventions for
representing text in the host environment. Thus, there need not be a
one-to-one correspondence between the characters in a stream and those in
the external representation. Data read in from a text stream will
necessarily compare equal to the data that were earlier written out to that
stream only if: the data consist only of printable characters and the
control characters horizontal tab and new-line; no new-line character is
immediately preceded by space characters; and the last character is a
new-line character. Whether space characters that are written out
immediately before a new-line character appear when read in is
implementation-defined.
A binary stream is an ordered sequence of characters that can
transparently record internal data. Data read in from a binary stream shall
compare equal to the data that were earlier written out to that stream,
under the same implementation. Such a stream may, however, have an
implementation-defined number of null characters appended.

"Environmental limits"

An implementation shall support text files with lines containing at least
254 characters, including the terminating new-line character. The value of
the macro BUFSIZ shall be at least 256.

4.9.3 Files

A stream is associated with an external file (which may be a physical
device) by opening a file, which may involve creating a new file. Creating
an existing file causes its former contents to be discarded, if necessary,
so that it appears as if newly created. If a file can support positioning
requests (such as a disk file, as opposed to a terminal), then a file
position indicator /100/file pointer .associated with the stream is
positioned at the start (character number zero) of the file, unless the file
is opened with append mode in which case it is implementation-defined
whether the file position indicator is positioned at the beginning or the
end of the file. The file position indicator is maintained by subsequent
reads, writes, and positioning requests, to facilitate an orderly
progression through the file. All input takes place as if characters were
read by successive calls to the fgetc function; all output takes place as if
characters were written by successive calls to the fputc function.
Binary files are not truncated, except as defined in $4.9.5.3. Whether a
write on a text stream causes the associated file to be truncated beyond
that point is implementation-defined.
When a stream is unbuffered , characters are intended to appear from the
source or at the destination as soon as possible. Otherwise characters may
be accumulated and transmitted to or from the host environment as a block.
When a stream is fully buffered ,characters are intended to be transmitted
to or from the host environment as a block when a buffer is filled. When a
stream is line buffered ,characters are intended to be transmitted to or
from the host environment as a block when a new-line character is
encountered. Furthermore, characters are intended to be transmitted as a
block to the host environment when a buffer is filled, when input is
requested on an unbuffered stream, or when input is requested on a line
buffered stream that requires the transmission of characters from the host
environment. Support for these characteristics is implementation-defined,
and may be affected via the setbuf and setvbuf functions.
A file may be disassociated from its controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is disassociated from
the file. The value of a pointer to a FILE object is indeterminate after

the associated file is closed (including the standard text streams).
Whether a file of zero length (on which no characters have been written by
an output stream) actually exists is implementation-defined.
The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be repositioned
at its start). If the main function returns to its original caller, or if
the exit function is called, all open files are closed (hence all output
streams are flushed) before program termination. Other paths to program
termination, such as calling the abort function, need not close all files
properly.
The address of the FILE object used to control a stream may be
significant; a copy of a FILE object may not necessarily serve in place of
the original.
At program startup, three text streams are predefined and need not be
opened explicitly --- standard input (for reading conventional input),
standard output (for writing conventional output), and standard error (for
writing diagnostic output). When opened, the standard error stream is not
fully buffered; the standard input and standard output streams are fully
buffered if and only if the stream can be determined not to refer to an
interactive device.
Functions that open additional (nontemporary) files require a file name
,which is a string. The rules for composing valid file names are
implementation-defined. Whether the same file can be simultaneously open
multiple times is also implementation-defined.

"Environmental limits"

The value of the macro FOPEN_MAX shall be at least eight, including the
three standard text streams.

Forward references: the exit function ($4.10.4.3), the fgetc function
($4.9.7.1), the fopen function ($4.9.5.3), the fputc function ($4.9.7.3),
the setbuf function ($4.9.5.5), the setvbuf function ($4.9.5.6).

4.9.4 Operations on files


4.9.4.1 The remove function


Synopsis


#include
int remove(const char *filename);



Description

The remove function causes the file whose name is the string pointed to
by filename to be no longer accessible by that name. A subsequent attempt
to open that file using that name will fail, unless it is created anew. If
the file is open, the behavior of the remove function is
implementation-defined.

Returns

The remove function returns zero if the operation succeeds, nonzero if it
fails.

4.9.4.2 The rename function


Synopsis


#include
int rename(const char *old, const char *new);



Description

The rename function causes the file whose name is the string pointed to
by old to be henceforth known by the name given by the string pointed to by
new . The file named old is effectively removed. If a file named by the
string pointed to by new exists prior to the call to the rename function,
the behavior is implementation-defined.

Returns

The rename function returns zero if the operation succeeds, nonzero if it
fails,/101/ in which case if the file existed previously it is still known
by its original name.

4.9.4.3 The tmpfile function


Synopsis


#include
FILE *tmpfile(void);



Description

The tmpfile function creates a temporary binary file that will
automatically be removed when it is closed or at program termination. If
the program terminates abnormally, whether an open temporary file is removed
is implementation-defined. The file is opened for update with wb+ mode.

Returns

The tmpfile function returns a pointer to the stream of the file that it
created. If the file cannot be created, the tmpfile function returns a null
pointer.

Forward references: the fopen function ($4.9.5.3).

4.9.4.4 The tmpnam function


Synopsis


#include
char *tmpnam(char *s);



Description

The tmpnam function generates a string that is a valid file name and that
is not the same as the name of an existing file./102/
The tmpnam function generates a different string each time it is called,
up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior
is implementation-defined.
The implementation shall behave as if no library function calls the
tmpnam function.


Returns

If the argument is a null pointer, the tmpnam function leaves its result
in an internal static object and returns a pointer to that object.
Subsequent calls to the tmpnam function may modify the same object. If the
argument is not a null pointer, it is assumed to point to an array of at
least L_tmpnam char s; the tmpnam function writes its result in that array
and returns the argument as its value.

"Environmental limits"

The value of the macro TMP_MAX shall be at least 25.

4.9.5 File access functions


4.9.5.1 The fclose function


Synopsis


#include
int fclose(FILE *stream);



Description

The fclose function causes the stream pointed to by stream to be flushed
and the associated file to be closed. Any unwritten buffered data for the
stream are delivered to the host environment to be written to the file; any
unread buffered data are discarded. The stream is disassociated from the
file. If the associated buffer was automatically allocated, it is
deallocated.

Returns

The fclose function returns zero if the stream was successfully closed,
or EOF if any errors were detected.

4.9.5.2 The fflush function


Synopsis


#include
int fflush(FILE *stream);



Description

If stream points to an output stream or an update stream in which the
most recent operation was output, the fflush function causes any unwritten
data for that stream to be delivered to the host environment to be written
to the file; otherwise, the behavior is undefined.
If stream is a null pointer, the fflush function performs this flushing
action on all streams for which the behavior is defined above.

Returns

The fflush function returns EOF if a write error occurs, otherwise zero.


Forward references: the ungetc function ($4.9.7.11).

4.9.5.3 The fopen function


Synopsis


#include
FILE *fopen(const char *filename, const char *mode);



Description

The fopen function opens the file whose name is the string pointed to by
filename , and associates a stream with it.
The argument mode points to a string beginning with one of the following
sequences:/103/

"r" open text file for reading
"w" truncate to zero length or create text file for
writing
"a" append; open or create text file for writing at
end-of-file
"rb" open binary file for reading
"wb" truncate to zero length or create binary file for
writing
"ab" append; open or create binary file for writing at
end-of-file
"r+" open text file for update (reading and writing)
"w+" truncate to zero length or create text file for
update
"a+" append; open or create text file for update,
writing at end-of-file
"r+b" or "rb+" open binary file for update (reading and writing)
"w+b" or "wb+" truncate to zero length or create binary file for update
"a+b" or "ab+" append; open or create binary file for update, writing at
end-of-file


Opening a file with read mode ('r' as the first character in the mode
argument) fails if the file does not exist or cannot be read.
Opening a file with append mode ('a' as the first character in the mode
argument) causes all subsequent writes to the file to be forced to the then
current end-of-file, regardless of intervening calls to the fseek function.
In some implementations, opening a binary file with append mode ('b' as the
second or third character in the mode argument) may initially position the
file position indicator for the stream beyond the last data written, because
of null character padding.
When a file is opened with update mode ('+' as the second or third
character in the mode argument), both input and output may be performed on
the associated stream. However, output may not be directly followed by
input without an intervening call to the fflush function or to a file
positioning function ( fseek , fsetpos , or rewind ), and input may not be
directly followed by output without an intervening call to a file
positioning function, unless the input operation encounters end-of-file.
Opening a file with update mode may open or create a binary stream in some
implementations.
When opened, a stream is fully buffered if and only if it can be
determined not to refer to an interactive device. The error and end-of-file
indicators for the stream are cleared.

Returns

The fopen function returns a pointer to the object controlling the
stream. If the open operation fails, fopen returns a null pointer.

Forward references: file positioning functions ($4.9.9).

4.9.5.4 The freopen function


Synopsis


#include
FILE *freopen(const char *filename, const char *mode,
FILE *stream);



Description

The freopen function opens the file whose name is the string pointed to
by filename and associates the stream pointed to by stream with it. The
mode argument is used just as in the fopen function./104/
The freopen function first attempts to close any file that is associated
with the specified stream. Failure to close the file successfully is
ignored. The error and end-of-file indicators for the stream are cleared.

Returns

The freopen function returns a null pointer if the open operation fails.
Otherwise, freopen returns the value of stream .

4.9.5.5 The setbuf function


Synopsis


#include
void setbuf(FILE *stream, char *buf);



Description

Except that it returns no value, the setbuf function is equivalent to the
setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size
, or (if buf is a null pointer), with the value _IONBF for mode .

Returns

The setbuf function returns no value.

Forward references: the setvbuf function ($4.9.5.6).

4.9.5.6 The setvbuf function


Synopsis


#include
int setvbuf(FILE *stream, char *buf, int mode, size_t size);



Description


The setvbuf function may be used after the stream pointed to by stream
has been associated with an open file but before any other operation is
performed on the stream. The argument mode determines how stream will be
buffered, as follows: _IOFBF causes input/output to be fully buffered;
_IOLBF causes output to be line buffered; _IONBF causes input/output to be
unbuffered. If buf is not a null pointer, the array it points to may be
used instead of a buffer allocated by the setvbuf function./105/ The
argument size specifies the size of the array. The contents of the array at
any time are indeterminate.

Returns

The setvbuf function returns zero on success, or nonzero if an invalid
value is given for mode or if the request cannot be honored.

4.9.6 Formatted input/output functions


4.9.6.1 The fprintf function


Synopsis


#include
int fprintf(FILE *stream, const char *format, ...);



Description

The fprintf function writes output to the stream pointed to by stream ,
under control of the string pointed to by format that specifies how
subsequent arguments are converted for output. If there are insufficient
arguments for the format, the behavior is undefined. If the format is
exhausted while arguments remain, the excess arguments are evaluated (as
always) but are otherwise ignored. The fprintf function returns when the
end of the format string is encountered.
The format shall be a multibyte character sequence, beginning and ending
in its initial shift state. The format is composed of zero or more
directives: ordinary multibyte characters (not % ), which are copied
unchanged to the output stream; and conversion specifications, each of which
results in fetching zero or more subsequent arguments. Each conversion
specification is introduced by the character % . After the % , the
following appear in sequence:

* Zero or more flags that modify the meaning of the conversion
specification.

* An optional decimal integer specifying a minimum field width ./106/ If
the converted value has fewer characters than the field width, it will be
padded with spaces on the left (or right, if the left adjustment flag,
described later, has been given) to the field width.

* An optional precision that gives the minimum number of digits to appear
for the d , i , o , u , x , and X conversions, the number of digits to
appear after the decimal-point character for e , E , and f conversions, the
maximum number of significant digits for the g and G conversions, or the
maximum number of characters to be written from a string in s conversion.
The precision takes the form of a period ( . ) followed by an optional
decimal integer; if the integer is omitted, it is treated as zero.

* An optional h specifying that a following d , i , o , u , x , or X
conversion specifier applies to a short int or unsigned short int argument
(the argument will have been promoted according to the integral promotions,

and its value shall be converted to short int or unsigned short int before
printing); an optional h specifying that a following n conversion specifier
applies to a pointer to a short int argument; an optional l (ell) specifying
that a following d , i , o , u , x , or X conversion specifier applies to a
long int or unsigned long int argument; an optional l specifying that a
following n conversion specifier applies to a pointer to a long int
argument; or an optional L specifying that a following e , E , f , g , or G
conversion specifier applies to a long double argument. If an h , l , or L
appears with any other conversion specifier, the behavior is undefined.

* A character that specifies the type of conversion to be applied.
A field width or precision, or both, may be indicated by an asterisk *
instead of a digit string. In this case, an int argument supplies the field
width or precision. The arguments specifying field width or precision, or
both, shall appear (in that order) before the argument (if any) to be
converted. A negative field width argument is taken as a - flag followed by
a positive field width. A negative precision argument is taken as if it
were missing.
The flag characters and their meanings are The result of the conversion
will be left-justified within the field. The result of a signed conversion
will always begin with a plus or minus sign. If the first character of a
signed conversion is not a sign, or if a signed conversion results in no
characters, a space will be prepended to the result. If the space and +
flags both appear, the space flag will be ignored. The result is to be
converted to an ``alternate form.'' For o conversion, it increases the
precision to force the first digit of the result to be a zero. For x (or X
) conversion, a nonzero result will have 0x (or 0X ) prepended to it. For e
, E , f , g , and G conversions, the result will always contain a
decimal-point character, even if no digits follow it (normally, a
decimal-point character appears in the result of these conversions only if a
digit follows it). For g and G conversions, trailing zeros will not be
removed from the result. For other conversions, the behavior is undefined.
For d , i , o , u , x , X , e , E , f , g , and G conversions, leading zeros
(following any indication of sign or base) are used to pad to the field
width; no space padding is performed. If the 0 and - flags both appear, the
0 flag will be ignored. For d , i , o , u , x , and X conversions, if a
precision is specified, the 0 flag will be ignored. For other conversions,
the behavior is undefined.
The conversion specifiers and their meanings are
The int argument is converted to signed decimal ( d or i ), unsigned
octal ( o ), unsigned decimal ( u ), or unsigned hexadecimal notation ( x or
X ); the letters abcdef are used for x conversion and the letters ABCDEF for
X conversion. The precision specifies the minimum number of digits to
appear; if the value being converted can be represented in fewer digits, it
will be expanded with leading zeros. The default precision is 1. The
result of converting a zero value with an explicit precision of zero is no
characters. The double argument is converted to decimal notation in the
style [-]ddd.ddd , where the number of digits after the decimal-point
character is equal to the precision specification. If the precision is
missing, it is taken as 6; if the precision is explicitly zero, no
decimal-point character appears. If a decimal-point character appears, at
least one digit appears before it. The value is rounded to the appropriate
number of digits. The double argument is converted in the style [-]d.ddde+-
dd , where there is one digit before the decimal-point character (which is
nonzero if the argument is nonzero) and the number of digits after it is
equal to the precision; if the precision is missing, it is taken as 6; if
the precision is zero, no decimal-point character appears. The value is
rounded to the appropriate number of digits. The E conversion specifier
will produce a number with E instead of e introducing the exponent. The
exponent always contains at least two digits. If the value is zero, the
exponent is zero. The double argument is converted in style f or e (or in
style E in the case of a G conversion specifier), with the precision
specifying the number of significant digits. If an explicit precision is
zero, it is taken as 1. The style used depends on the value converted;
style e will be used only if the exponent resulting from such a conversion
is less than -4 or greater than or equal to the precision. Trailing zeros

are removed from the fractional portion of the result; a decimal-point
character appears only if it is followed by a digit. The int argument is
converted to an unsigned char , and the resulting character is written. The
argument shall be a pointer to an array of character type./107/
Characters from the array are written up to (but not including) a
terminating null character; if the precision is specified, no more than that
many characters are written. If the precision is not specified or is
greater than the size of the array, the array shall contain a null
character. The argument shall be a pointer to void . The value of the
pointer is converted to a sequence of printable characters, in an
implementation-defined manner. The argument shall be a pointer to an
integer into which is written the number of characters written to the output
stream so far by this call to fprintf . No argument is converted. A % is
written. No argument is converted. The complete conversion specification
shall be %% .
If a conversion specification is invalid, the behavior is undefined./108/

If any argument is, or points to, a union or an aggregate (except for an
array of character type using %s conversion, or a pointer cast to be a
pointer to void using %p conversion), the behavior is undefined.
In no case does a nonexistent or small field width cause truncation of a
field; if the result of a conversion is wider than the field width, the
field is expanded to contain the conversion result.

Returns

The fprintf function returns the number of characters transmitted, or a
negative value if an output error occurred.

"Environmental limit"

The minimum value for the maximum number of characters produced by any
single conversion shall be 509.

Examples

To print a date and time in the form ``Sunday, July 3, 10:02,'' where
weekday and month are pointers to strings:

#include
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
weekday, month, day, hour, min);

To print PI to five decimal places:

#include
#include
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));



4.9.6.2 The fscanf function


Synopsis


#include
int fscanf(FILE *stream, const char *format, ...);



Description

The fscanf function reads input from the stream pointed to by stream ,
under control of the string pointed to by format that specifies the

admissible input sequences and how they are to be converted for assignment,
using subsequent arguments as pointers to the objects to receive the
converted input. If there are insufficient arguments for the format, the
behavior is undefined. If the format is exhausted while arguments remain,
the excess arguments are evaluated (as always) but are otherwise ignored.
The format shall be a multibyte character sequence, beginning and ending
in its initial shift state. The format is composed of zero or more
directives: one or more white-space characters; an ordinary multibyte
character (not % ); or a conversion specification. Each conversion
specification is introduced by the character % . After the % , the
following appear in sequence:

* An optional assignment-suppressing character * .

* An optional decimal integer that specifies the maximum field width.

* An optional h , l (ell) or L indicating the size of the receiving object.
The conversion specifiers d , i , and n shall be preceded by h if the
corresponding argument is a pointer to short int rather than a pointer to
int , or by l if it is a pointer to long int . Similarly, the conversion
specifiers o , u , and x shall be preceded by h if the corresponding
argument is a pointer to unsigned short int rather than a pointer to
unsigned int , or by l if it is a pointer to unsigned long int . Finally,
the conversion specifiers e , f , and g shall be preceded by l if the
corresponding argument is a pointer to double rather than a pointer to float
, or by L if it is a pointer to long double . If an h , l , or L appears
with any other conversion specifier, the behavior is undefined.

* A character that specifies the type of conversion to be applied. The
valid conversion specifiers are described below.
The fscanf function executes each directive of the format in turn. If a
directive fails, as detailed below, the fscanf function returns. Failures
are described as input failures (due to the unavailability of input
characters), or matching failures (due to inappropriate input).
A directive composed of white space is executed by reading input up to
the first non-white-space character (which remains unread), or until no more
characters can be read.
A directive that is an ordinary multibyte character is executed by
reading the next characters of the stream. If one of the characters differs
from one comprising the directive, the directive fails, and the differing
and subsequent characters remain unread.
A directive that is a conversion specification defines a set of matching
input sequences, as described below for each specifier. A conversion
specification is executed in the following steps:
Input white-space characters (as specified by the isspace function) are
skipped, unless the specification includes a [ , c , or n specifier.
An input item is read from the stream, unless the specification includes
an n specifier. An input item is defined as the longest sequence of input
characters (up to any specified maximum field width) which is an initial
subsequence of a matching sequence. The first character, if any, after the
input item remains unread. If the length of the input item is zero, the
execution of the directive fails: this condition is a matching failure,
unless an error prevented input from the stream, in which case it is an
input failure.
Except in the case of a % specifier, the input item (or, in the case of a
%n directive, the count of input characters) is converted to a type
appropriate to the conversion specifier. If the input item is not a
matching sequence, the execution of the directive fails: this condition is a
matching failure. Unless assignment suppression was indicated by a * , the
result of the conversion is placed in the object pointed to by the first
argument following the format argument that has not already received a
conversion result. If this object does not have an appropriate type, or if
the result of the conversion cannot be represented in the space provided,
the behavior is undefined.
The following conversion specifiers are valid:
Matches an optionally signed decimal integer, whose format is the same as

expected for the subject sequence of the strtol function with the value 10
for the base argument. The corresponding argument shall be a pointer to
integer. Matches an optionally signed integer, whose format is the same as
expected for the subject sequence of the strtol function with the value 0
for the base argument. The corresponding argument shall be a pointer to
integer. Matches an optionally signed octal integer, whose format is the
same as expected for the subject sequence of the strtoul function with the

value 8 for the base argument. The corresponding argument shall be a
pointer to unsigned integer. Matches an optionally signed decimal integer,
whose format is the same as expected for the subject sequence of the strtoul
function with the value 10 for the base argument. The corresponding
argument shall be a pointer to unsigned integer. Matches an optionally
signed hexadecimal integer, whose format is the same as expected for the
subject sequence of the strtoul function with the value 16 for the base
argument. The corresponding argument shall be a pointer to unsigned
integer. Matches an optionally signed floating-point number, whose format
is the same as expected for the subject string of the strtod function. The
corresponding argument shall be a pointer to floating. Matches a sequence
of non-white-space characters.rN The corresponding argument shall be a
pointer to the initial character of an array large enough to accept the
sequence and a terminating null character, which will be added
automatically. Matches a nonempty sequence of charactersrN from a set of
expected characters (the scanset ). The corresponding argument shall be a
pointer to the initial character of an array large enough to accept the
sequence and a terminating null character, which will be added
automatically. The conversion specifier includes all subsequent characters
in the format string, up to and including the matching right bracket ( ] ).
The characters between the brackets (the scanlist ) comprise the scanset,
unless the character after the left bracket is a circumflex ( ^ ), in which
case the scanset contains all characters that do not appear in the scanlist
between the circumflex and the right bracket. As a special case, if the
conversion specifier begins with [] or [^] , the right bracket character is
in the scanlist and the next right bracket character is the matching right
bracket that ends the specification. If a - character is in the scanlist
and is not the first, nor the second where the first character is a ^ , nor
the last character, the behavior is implementation-defined. Matches a
sequence of charactersrN of the number specified by the field width (1 if no
field width is present in the directive). The corresponding argument shall
be a pointer to the initial character of an array large enough to accept the
sequence. No null character is added. Matches an implementation-defined
set of sequences, which should be the same as the set of sequences that may
be produced by the %p conversion of the fprintf function. The corresponding
argument shall be a pointer to a pointer to void . The interpretation of
the input item is implementation-defined; however, for any input item other
than a value converted earlier during the same program execution, the
behavior of the %p conversion is undefined. No input is consumed. The
corresponding argument shall be a pointer to integer into which is to be
written the number of characters read from the input stream so far by this
call to the fscanf function. Execution of a %n directive does not increment
the assignment count returned at the completion of execution of the fscanf
function. Matches a single % ; no conversion or assignment occurs. The
complete conversion specification shall be %% .
If a conversion specification is invalid, the behavior is undefined./110/

The conversion specifiers E , G , and X are also valid and behave the
same as, respectively, e , g , and x .
If end-of-file is encountered during input, conversion is terminated. If
end-of-file occurs before any characters matching the current directive have
been read (other than leading white space, where permitted), execution of
the current directive terminates with an input failure; otherwise, unless
execution of the current directive is terminated with a matching failure,
execution of the following directive (if any) is terminated with an input
failure.
If conversion terminates on a conflicting input character, the offending
input character is left unread in the input stream. Trailing white space
(including new-line characters) is left unread unless matched by a

directive. The success of literal matches and suppressed assignments is not
directly determinable other than via the %n directive.

Returns

The fscanf function returns the value of the macro EOF if an input
failure occurs before any conversion. Otherwise, the fscanf function
returns the number of input items assigned, which can be fewer than provided
for, or even zero, in the event of an early matching failure.

Examples

The call:

#include
int n, i; float x; char name[50];
n = fscanf(stdin, "%d%f%s", &i, &x, name);

with the input line:

25 54.32E-1 thompson

will assign to n the value 3, to i the value 25, to x the value 5.432, and
name will contain thompson\0 . Or:

#include
int i; float x; char name[50];
fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name);

with input:

56789 0123 56a72

will assign to i the value 56 and to x the value 789.0, will skip 0123, and
name will contain 56\0 . The next character read from the input stream will
be a .
To accept repeatedly from stdin a quantity, a unit of measure and an item
name:

#include
int count; float quant; char units[21], item[21];
while (!feof(stdin) && !ferror(stdin)) {
count = fscanf(stdin, "%f%20s of %20s",
&quant, units, item);
fscanf(stdin,"%*[^\n]");
}


If the stdin stream contains the following lines:

2 quarts of oil
-12.8degrees Celsius
lots of luck
10.0LBS of fertilizer
100ergs of energy

the execution of the above example will be equivalent to the following
assignments:

quant = 2; strcpy(units, "quarts"); strcpy(item, "oil");
count = 3;
quant = -12.8; strcpy(units, "degrees");
count = 2; /* "C" fails to match "o" */
count = 0; /* "l" fails to match "%f" */
quant = 10.0; strcpy(units, "LBS"); strcpy(item, "fertilizer");
count = 3;

count = 0; /* "100e" fails to match "%f" */
count = EOF;



Forward references: the strtod function ($4.10.1.4), the strtol function
($4.10.1.5), the strtoul function ($4.10.1.6).

4.9.6.3 The printf function


Synopsis


#include
int printf(const char *format, ...);



Description

The printf function is equivalent to fprintf with the argument stdout
interposed before the arguments to printf .

Returns

The printf function returns the number of characters transmitted, or a
negative value if an output error occurred.

4.9.6.4 The scanf function


Synopsis


#include
int scanf(const char *format, ...);



Description

The scanf function is equivalent to fscanf with the argument stdin
interposed before the arguments to scanf .

Returns

The scanf function returns the value of the macro EOF if an input failure
occurs before any conversion. Otherwise, the scanf function returns the
number of input items assigned, which can be fewer than provided for, or
even zero, in the event of an early matching failure.

4.9.6.5 The sprintf function


Synopsis


#include
int sprintf(char *s, const char *format, ...);



Description

The sprintf function is equivalent to fprintf , except that the argument

s specifies an array into which the generated output is to be written,
rather than to a stream. A null character is written at the end of the
characters written; it is not counted as part of the returned sum. If
copying takes place between objects that overlap, the behavior is undefined.


Returns

The sprintf function returns the number of characters written in the
array, not counting the terminating null character.

4.9.6.6 The sscanf function


Synopsis


#include
int sscanf(const char *s, const char *format, ...);



Description

The sscanf function is equivalent to fscanf , except that the argument s
specifies a string from which the input is to be obtained, rather than from
a stream. Reaching the end of the string is equivalent to encountering
end-of-file for the fscanf function. If copying takes place between objects
that overlap, the behavior is undefined.

Returns

The sscanf function returns the value of the macro EOF if an input
failure occurs before any conversion. Otherwise, the sscanf function
returns the number of input items assigned, which can be fewer than provided
for, or even zero, in the event of an early matching failure.

4.9.6.7 The vfprintf function


Synopsis


#include
#include
int vfprintf(FILE *stream, const char *format, va_list arg);



Description

The vfprintf function is equivalent to fprintf , with the variable
argument list replaced by arg , which has been initialized by the va_start
macro (and possibly subsequent va_arg calls). The vfprintf function does
not invoke the va_end macro.rN

Returns

The vfprintf function returns the number of characters transmitted, or a
negative value if an output error occurred.

Example

The following shows the use of the vfprintf function in a general
error-reporting routine.

#include
#include

void error(char *function_name, char *format, ...)
{
va_list args;

va_start(args, format);
/* print out name of function causing error */
fprintf(stderr, "ERROR in %s: ", function_name);
/* print out remainder of message */
vfprintf(stderr, format, args);
va_end(args);
}



4.9.6.8 The vprintf function


Synopsis


#include
#include
int vprintf(const char *format, va_list arg);



Description

The vprintf function is equivalent to printf , with the variable argument
list replaced by arg , which has been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vprintf function does not invoke the
va_end macro.rN

Returns

The vprintf function returns the number of characters transmitted, or a
negative value if an output error occurred.

4.9.6.9 The vsprintf function


Synopsis


#include
#include
int vsprintf(char *s, const char *format, va_list arg);



Description

The vsprintf function is equivalent to sprintf , with the variable
argument list replaced by arg , which has been initialized by the va_start
macro (and possibly subsequent va_arg calls). The vsprintf function does
not invoke the va_end macro.rN If copying takes place between objects that
overlap, the behavior is undefined.

Returns

The vsprintf function returns the number of characters written in the
array, not counting the terminating null character.

4.9.7 Character input/output functions


4.9.7.1 The fgetc function


Synopsis


#include
int fgetc(FILE *stream);



Description

The fgetc function obtains the next character (if present) as an unsigned
char converted to an int , from the input stream pointed to by stream , and
advances the associated file position indicator for the stream (if defined).


Returns

The fgetc function returns the next character from the input stream
pointed to by stream . If the stream is at end-of-file, the end-of-file
indicator for the stream is set and fgetc returns EOF . If a read error
occurs, the error indicator for the stream is set and fgetc returns EOF
./112/

4.9.7.2 The fgets function


Synopsis


#include
char *fgets(char *s, int n, FILE *stream);



Description

The fgets function reads at most one less than the number of characters
specified by n from the stream pointed to by stream into the array pointed
to by s . No additional characters are read after a new-line character
(which is retained) or after end-of-file. A null character is written
immediately after the last character read into the array.

Returns

The fgets function returns s if successful. If end-of-file is
encountered and no characters have been read into the array, the contents of
the array remain unchanged and a null pointer is returned. If a read error
occurs during the operation, the array contents are indeterminate and a null
pointer is returned.

4.9.7.3 The fputc function


Synopsis


#include
int fputc(int c, FILE *stream);



Description

The fputc function writes the character specified by c (converted to an
unsigned char ) to the output stream pointed to by stream , at the position
indicated by the associated file position indicator for the stream (if
defined), and advances the indicator appropriately. If the file cannot
support positioning requests, or if the stream was opened with append mode,
the character is appended to the output stream.

Returns

The fputc function returns the character written. If a write error
occurs, the error indicator for the stream is set and fputc returns EOF .

4.9.7.4 The fputs function


Synopsis


#include
int fputs(const char *s, FILE *stream);



Description

The fputs function writes the string pointed to by s to the stream
pointed to by stream . The terminating null character is not written.


Returns

The fputs function returns EOF if a write error occurs; otherwise it
returns a nonnegative value.

4.9.7.5 The getc function


Synopsis


#include
int getc(FILE *stream);



Description

The getc function is equivalent to fgetc , except that if it is
implemented as a macro, it may evaluate stream more than once, so the
argument should never be an expression with side effects.

Returns

The getc function returns the next character from the input stream
pointed to by stream . If the stream is at end-of-file, the end-of-file
indicator for the stream is set and getc returns EOF . If a read error
occurs, the error indicator for the stream is set and getc returns EOF .

4.9.7.6 The getchar function


Synopsis


#include
int getchar(void);



Description

The getchar function is equivalent to getc with the argument stdin .

Returns

The getchar function returns the next character from the input stream
pointed to by stdin . If the stream is at end-of-file, the end-of-file
indicator for the stream is set and getchar returns EOF . If a read error
occurs, the error indicator for the stream is set and getchar returns EOF .


4.9.7.7 The gets function


Synopsis


#include
char *gets(char *s);



Description

The gets function reads characters from the input stream pointed to by
stdin , into the array pointed to by s , until end-of-file is encountered or
a new-line character is read. Any new-line character is discarded, and a
null character is written immediately after the last character read into the
array.

Returns

The gets function returns s if successful. If end-of-file is encountered
and no characters have been read into the array, the contents of the array
remain unchanged and a null pointer is returned. If a read error occurs
during the operation, the array contents are indeterminate and a null
pointer is returned.

4.9.7.8 The putc function


Synopsis


#include
int putc(int c, FILE *stream);



Description

The putc function is equivalent to fputc , except that if it is
implemented as a macro, it may evaluate stream more than once, so the
argument should never be an expression with side effects.

Returns

The putc function returns the character written. If a write error
occurs, the error indicator for the stream is set and putc returns EOF .

4.9.7.9 The putchar function


Synopsis


#include
int putchar(int c);



Description

The putchar function is equivalent to putc with the second argument
stdout .

Returns

The putchar function returns the character written. If a write error
occurs, the error indicator for the stream is set and putchar returns EOF .


4.9.7.10 The puts function


Synopsis


#include
int puts(const char *s);



Description

The puts function writes the string pointed to by s to the stream pointed
to by stdout , and appends a new-line character to the output. The
terminating null character is not written.

Returns

The puts function returns EOF if a write error occurs; otherwise it
returns a nonnegative value.

4.9.7.11 The ungetc function


Synopsis


#include
int ungetc(int c, FILE *stream);



Description

The ungetc function pushes the character specified by c (converted to an
unsigned char ) back onto the input stream pointed to by stream . The
pushed-back characters will be returned by subsequent reads on that stream
in the reverse order of their pushing. A successful intervening call (with
the stream pointed to by stream ) to a file positioning function ( fseek ,
fsetpos , or rewind ) discards any pushed-back characters for the stream.
The external storage corresponding to the stream is unchanged.
One character of pushback is guaranteed. If the ungetc function is
called too many times on the same stream without an intervening read or file

positioning operation on that stream, the operation may fail.
If the value of c equals that of the macro EOF , the operation fails and
the input stream is unchanged.
A successful call to the ungetc function clears the end-of-file indicator
for the stream. The value of the file position indicator for the stream
after reading or discarding all pushed-back characters shall be the same as
it was before the characters were pushed back. For a text stream, the value
of its file position indicator after a successful call to the ungetc
function is unspecified until all pushed-back characters are read or
discarded. For a binary stream, its file position indicator is decremented
by each successful call to the ungetc function; if its value was zero before
a call, it is indeterminate after the call.

Returns

The ungetc function returns the character pushed back after conversion,
or EOF if the operation fails.

Forward references: file positioning functions ($4.9.9).

4.9.8 Direct input/output functions


4.9.8.1 The fread function


Synopsis


#include
size_t fread(void *ptr, size_t size, size_t nmemb,
FILE *stream);



Description

The fread function reads, into the array pointed to by ptr , up to nmemb
members whose size is specified by size , from the stream pointed to by
stream . The file position indicator for the stream (if defined) is
advanced by the number of characters successfully read. If an error occurs,
the resulting value of the file position indicator for the stream is
indeterminate. If a partial member is read, its value is indeterminate.

Returns

The fread function returns the number of members successfully read, which
may be less than nmemb if a read error or end-of-file is encountered. If
size or nmemb is zero, fread returns zero and the contents of the array and
the state of the stream remain unchanged.

4.9.8.2 The fwrite function


Synopsis


#include
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);



Description

The fwrite function writes, from the array pointed to by ptr , up to

nmemb members whose size is specified by size , to the stream pointed to by
stream . The file position indicator for the stream (if defined) is
advanced by the number of characters successfully written. If an error
occurs, the resulting value of the file position indicator for the stream is
indeterminate.

Returns

The fwrite function returns the number of members successfully written,
which will be less than nmemb only if a write error is encountered.

4.9.9 File positioning functions


4.9.9.1 The fgetpos function


Synopsis


#include
int fgetpos(FILE *stream, fpos_t *pos);



Description

The fgetpos function stores the current value of the file position
indicator for the stream pointed to by stream in the object pointed to by
pos . The value stored contains unspecified information usable by the
fsetpos function for repositioning the stream to its position at the time of
the call to the fgetpos function.

Returns

If successful, the fgetpos function returns zero; on failure, the fgetpos
function returns nonzero and stores an implementation-defined positive value
in errno .

Forward references: the fsetpos function ($4.9.9.3).

4.9.9.2 The fseek function


Synopsis


#include
int fseek(FILE *stream, long int offset, int whence);



Description

The fseek function sets the file position indicator for the stream
pointed to by stream .
For a binary stream, the new position, measured in characters from the
beginning of the file, is obtained by adding offset to the position
specified by whence . The specified point is the beginning of the file for
SEEK_SET , the current value of the file position indicator for SEEK_CUR ,
or end-of-file for SEEK_END . A binary stream need not meaningfully support
fseek calls with a whence value of SEEK_END .
For a text stream, either offset shall be zero, or offset shall be a
value returned by an earlier call to the ftell function on the same stream
and whence shall be SEEK_SET .
A successful call to the fseek function clears the end-of-file indicator

for the stream and undoes any effects of the ungetc function on the same
stream. After an fseek call, the next operation on an update stream may be
either input or output.

Returns

The fseek function returns nonzero only for a request that cannot be
satisfied.

Forward references: the ftell function ($4.9.9.4).

4.9.9.3 The fsetpos function


Synopsis


#include
int fsetpos(FILE *stream, const fpos_t *pos);



Description

The fsetpos function sets the file position indicator for the stream
pointed to by stream according to the value of the object pointed to by pos
, which shall be a value returned by an earlier call to the fgetpos function
on the same stream.
A successful call to the fsetpos function clears the end-of-file
indicator for the stream and undoes any effects of the ungetc function on
the same stream. After an fsetpos call, the next operation on an update
stream may be either input or output.

Returns

If successful, the fsetpos function returns zero; on failure, the fsetpos
function returns nonzero and stores an implementation-defined positive value
in errno .

4.9.9.4 The ftell function


Synopsis


#include
long int ftell(FILE *stream);



Description

The ftell function obtains the current value of the file position
indicator for the stream pointed to by stream . For a binary stream, the
value is the number of characters from the beginning of the file. For a
text stream, its file position indicator contains unspecified information,
usable by the fseek function for returning the file position indicator for
the stream to its position at the time of the ftell call; the difference
between two such return values is not necessarily a meaningful measure of
the number of characters written or read.

Returns

If successful, the ftell function returns the current value of the file
position indicator for the stream. On failure, the ftell function returns
-1L and stores an implementation-defined positive value in errno .


4.9.9.5 The rewind function


Synopsis


#include
void rewind(FILE *stream);



Description

The rewind function sets the file position indicator for the stream
pointed to by stream to the beginning of the file. It is equivalent to

(void)fseek(stream, 0L, SEEK_SET)

except that the error indicator for the stream is also cleared.

Returns

The rewind function returns no value.

4.9.10 Error-handling functions


4.9.10.1 The clearerr function


Synopsis


#include
void clearerr(FILE *stream);



Description

The clearerr function clears the end-of-file and error indicators for the
stream pointed to by stream .

Returns

The clearerr function returns no value.

4.9.10.2 The feof function


Synopsis


#include
int feof(FILE *stream);



Description

The feof function tests the end-of-file indicator for the stream pointed
to by stream .

Returns

The feof function returns nonzero if and only if the end-of-file
indicator is set for stream .

4.9.10.3 The ferror function


Synopsis


#include
int ferror(FILE *stream);



Description

The ferror function tests the error indicator for the stream pointed to
by stream .

Returns

The ferror function returns nonzero if and only if the error indicator is
set for stream .

4.9.10.4 The perror function


Synopsis


#include
void perror(const char *s);



Description

The perror function maps the error number in the integer expression errno
to an error message. It writes a sequence of characters to the standard
error stream thus: first (if s is not a null pointer and the character
pointed to by s is not the null character), the string pointed to by s
followed by a colon and a space; then an appropriate error message string
followed by a new-line character. The contents of the error message strings
are the same as those returned by the strerror function with argument errno
, which are implementation-defined.

Returns

The perror function returns no value.

Forward references: the strerror function ($4.11.6.2).


4.10 GENERAL UTILITIES

The header declares four types and several functions of
general utility, and defines several macros./113/
The types declared are size_t and wchar_t (both described in $4.1.5),

div_t

which is a structure type that is the type of the value returned by the div
function, and

ldiv_t

which is a structure type that is the type of the value returned by the ldiv
function.
The macros defined are NULL (described in $4.1.5);

EXIT_FAILURE

and

EXIT_SUCCESS

which expand to integral expressions that may be used as the argument to the
exit function to return unsuccessful or successful termination status,
respectively, to the host environment;

RAND_MAX

which expands to an integral constant expression, the value of which is the
maximum value returned by the rand function; and

MB_CUR_MAX

which expands to a positive integer expression whose value is the maximum
number of bytes in a multibyte character for the extended character set
specified by the current locale (category LC_CTYPE ), and whose value is
never greater than MB_LEN_MAX .

4.10.1 String conversion functions

The functions atof , atoi , and atol need not affect the value of the
integer expression errno on an error. If the value of the result cannot be
represented, the behavior is undefined.

4.10.1.1 The atof function


Synopsis


#include
double atof(const char *nptr);



Description

The atof function converts the initial portion of the string pointed to
by nptr to double representation. Except for the behavior on error, it is
equivalent to

strtod(nptr, (char **)NULL)



Returns

The atof function returns the converted value.

Forward references: the strtod function ($4.10.1.4).

4.10.1.2 The atoi function


Synopsis


#include

int atoi(const char *nptr);



Description

The atoi function converts the initial portion of the string pointed to
by nptr to int representation. Except for the behavior on error, it is
equivalent to

(int)strtol(nptr, (char **)NULL, 10)



Returns

The atoi function returns the converted value.

Forward references: the strtol function ($4.10.1.5).

4.10.1.3 The atol function


Synopsis


#include
long int atol(const char *nptr);



Description

The atol function converts the initial portion of the string pointed to
by nptr to long int representation. Except for the behavior on error, it is
equivalent to

strtol(nptr, (char **)NULL, 10)



Returns

The atol function returns the converted value.

Forward references: the strtol function ($4.10.1.5).

4.10.1.4 The strtod function


Synopsis


#include
double strtod(const char *nptr, char **endptr);



Description

The strtod function converts the initial portion of the string pointed to
by nptr to double representation. First it decomposes the input string into
three parts: an initial, possibly empty, sequence of white-space characters
(as specified by the isspace function), a subject sequence resembling a
floating-point constant; and a final string of one or more unrecognized
characters, including the terminating null character of the input string.

Then it attempts to convert the subject sequence to a floating-point number,
and returns the result.
The expected form of the subject sequence is an optional plus or minus
sign, then a nonempty sequence of digits optionally containing a
decimal-point character, then an optional exponent part as defined in
$3.1.3.1, but no floating suffix. The subject sequence is defined as the
longest subsequence of the input string, starting with the first
non-white-space character, that is an initial subsequence of a sequence of
the expected form. The subject sequence contains no characters if the input
string is empty or consists entirely of white space, or if the first
non-white-space character is other than a sign, a digit, or a decimal-point
character.
If the subject sequence has the expected form, the sequence of characters
starting with the first digit or the decimal-point character (whichever
occurs first) is interpreted as a floating constant according to the rules
of $3.1.3.1, except that the decimal-point character is used in place of a
period, and that if neither an exponent part nor a decimal-point character
appears, a decimal point is assumed to follow the last digit in the string.
If the subject sequence begins with a minus sign, the value resulting from
the conversion is negated. A pointer to the final string is stored in the
object pointed to by endptr , provided that endptr is not a null pointer.
In other than the C locale, additional implementation-defined subject
sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no
conversion is performed; the value of nptr is stored in the object pointed
to by endptr , provided that endptr is not a null pointer.

Returns

The strtod function returns the converted value, if any. If no
conversion could be performed, zero is returned. If the correct value would
cause overflow, plus or minus HUGE_VAL is returned (according to the sign of
the value), and the value of the macro ERANGE is stored in errno . If the
correct value would cause underflow, zero is returned and the value of the
macro ERANGE is stored in errno .

4.10.1.5 The strtol function


Synopsis


#include
long int strtol(const char *nptr, char **endptr, int base);



Description

The strtol function converts the initial portion of the string pointed to
by nptr to long int representation. First it decomposes the input string
into three parts: an initial, possibly empty, sequence of white-space
characters (as specified by the isspace function), a subject sequence
resembling an integer represented in some radix determined by the value of
base , and a final string of one or more unrecognized characters, including
the terminating null character of the input string. Then it attempts to
convert the subject sequence to an integer, and returns the result.
If the value of base is zero, the expected form of the subject sequence
is that of an integer constant as described in $3.1.3.2, optionally preceded
by a plus or minus sign, but not including an integer suffix. If the value
of base is between 2 and 36, the expected form of the subject sequence is a
sequence of letters and digits representing an integer with the radix
specified by base , optionally preceded by a plus or minus sign, but not
including an integer suffix. The letters from a (or A ) through z (or Z )
are ascribed the values 10 to 35; only letters whose ascribed values are
less than that of base are permitted. If the value of base is 16, the

characters 0x or 0X may optionally precede the sequence of letters and
digits, following the sign if present.
The subject sequence is defined as the longest subsequence of the input
string, starting with the first non-white-space character, that is an
initial subsequence of a sequence of the expected form. The subject
sequence contains no characters if the input string is empty or consists
entirely of white space, or if the first non-white-space character is other
than a sign or a permissible letter or digit.
If the subject sequence has the expected form and the value of base is
zero, the sequence of characters starting with the first digit is
interpreted as an integer constant according to the rules of $3.1.3.2. If
the subject sequence has the expected form and the value of base is between
2 and 36, it is used as the base for conversion, ascribing to each letter
its value as given above. If the subject sequence begins with a minus sign,
the value resulting from the conversion is negated. A pointer to the final
string is stored in the object pointed to by endptr , provided that endptr
is not a null pointer.
In other than the C locale, additional implementation-defined subject
sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no
conversion is performed; the value of nptr is stored in the object pointed
to by endptr , provided that endptr is not a null pointer.

Returns

The strtol function returns the converted value, if any. If no
conversion could be performed, zero is returned. If the correct value would
cause overflow, LONG_MAX or LONG_MIN is returned (according to the sign of
the value), and the value of the macro ERANGE is stored in errno .

4.10.1.6 The strtoul function


Synopsis


#include
unsigned long int strtoul(const char *nptr, char **endptr,
int base);



Description

The strtoul function converts the initial portion of the string pointed
to by nptr to unsigned long int representation. First it decomposes the
input string into three parts: an initial, possibly empty, sequence of
white-space characters (as specified by the isspace function), a subject
sequence resembling an unsigned integer represented in some radix determined
by the value of base , and a final string of one or more unrecognized
characters, including the terminating null character of the input string.
Then it attempts to convert the subject sequence to an unsigned integer, and
returns the result.
If the value of base is zero, the expected form of the subject sequence
is that of an integer constant as described in $3.1.3.2, optionally preceded
by a plus or minus sign, but not including an integer suffix. If the value
of base is between 2 and 36, the expected form of the subject sequence is a
sequence of letters and digits representing an integer with the radix
specified by base , optionally preceded by a plus or minus sign, but not
including an integer suffix. The letters from a (or A ) through z (or Z )
are ascribed the values 10 to 35; only letters whose ascribed values are
less than that of base are permitted. If the value of base is 16, the
characters 0x or 0X may optionally precede the sequence of letters and
digits, following the sign if present.
The subject sequence is defined as the longest subsequence of the input
string, starting with the first non-white-space character, that is an

initial subsequence of a sequence of the expected form. The subject
sequence contains no characters if the input string is empty or consists
entirely of white space, or if the first non-white-space character is other
than a sign or a permissible letter or digit.
If the subject sequence has the expected form and the value of base is
zero, the sequence of characters starting with the first digit is
interpreted as an integer constant according to the rules of $3.1.3.2. If
the subject sequence has the expected form and the value of base is between
2 and 36, it is used as the base for conversion, ascribing to each letter
its value as given above. If the subject sequence begins with a minus sign,
the value resulting from the conversion is negated. A pointer to the final
string is stored in the object pointed to by endptr , provided that endptr
is not a null pointer.
In other than the C locale, additional implementation-defined subject
sequence forms may be accepted.
If the subject sequence is empty or does not have the expected form, no
conversion is performed; the value of nptr is stored in the object pointed
to by endptr , provided that endptr is not a null pointer.

Returns

The strtoul function returns the converted value, if any. If no
conversion could be performed, zero is returned. If the correct value would
cause overflow, ULONG_MAX is returned, and the value of the macro ERANGE is
stored in errno .

4.10.2 Pseudo-random sequence generation functions


4.10.2.1 The rand function


Synopsis


#include
int rand(void);



Description

The rand function computes a sequence of pseudo-random integers in the
range 0 to RAND_MAX .
The implementation shall behave as if no library function calls the rand
function.

Returns

The rand function returns a pseudo-random integer.

"Environmental limit"

The value of the RAND_MAX macro shall be at least 32767.

4.10.2.2 The srand function


Synopsis


#include
void srand(unsigned int seed);



Description

The srand function uses the argument as a seed for a new sequence of
pseudo-random numbers to be returned by subsequent calls to rand . If srand
is then called with the same seed value, the sequence of pseudo-random
numbers shall be repeated. If rand is called before any calls to srand have
been made, the same sequence shall be generated as when srand is first
called with a seed value of 1.
The implementation shall behave as if no library function calls the srand
function.

Returns

The srand function returns no value.

Example

The following functions define a portable implementation of rand and
srand . Specifying the semantics makes it possible to determine
reproducibly the behavior of programs that use pseudo-random sequences.
This facilitates the testing of portable applications in different
implementations.

static unsigned long int next = 1;

int rand(void) /* RAND_MAX assumed to be 32767 */
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed)
{
next = seed;
}



4.10.3 Memory management functions

The order and contiguity of storage allocated by successive calls to the
calloc , malloc , and realloc functions is unspecified. The pointer
returned if the allocation succeeds is suitably aligned so that it may be
assigned to a pointer to any type of object and then used to access such an
object in the space allocated (until the space is explicitly freed or
reallocated). Each such allocation shall yield a pointer to an object
disjoint from any other object. The pointer returned points to the start
(lowest byte address) of the allocated space. If the space cannot be
allocated, a null pointer is returned. If the size of the space requested
is zero, the behavior is implementation-defined; the value returned shall be
either a null pointer or a unique pointer. The value of a pointer that
refers to freed space is indeterminate.


4.10.3.1 The calloc function

Synopsis

#include
void *calloc(size_t nmemb, size_t size);



Description

The calloc function allocates space for an array of nmemb objects, each
of whose size is size . The space is initialized to all bits zero./114/

Returns

The calloc function returns either a null pointer or a pointer to the
allocated space.


4.10.3.2 The free function

Synopsis

#include
void free(void *ptr);

Description

The free function causes the space pointed to by ptr to be deallocated,
that is, made available for further allocation. If ptr is a null pointer,
no action occurs. Otherwise, if the argument does not match a pointer
earlier returned by the calloc , malloc , or realloc function, or if the
space has been deallocated by a call to free or realloc , the behavior is
undefined.

Returns

The free function returns no value.


4.10.3.3 The malloc function

Synopsis


#include
void *malloc(size_t size);

Description

The malloc function allocates space for an object whose size is specified
by size and whose value is indeterminate.

Returns

The malloc function returns either a null pointer or a pointer to the
allocated space.


4.10.3.4 The realloc function

Synopsis

#include
void *realloc(void *ptr, size_t size);

Description

The realloc function changes the size of the object pointed to by ptr to
the size specified by size . The contents of the object shall be unchanged
up to the lesser of the new and old sizes. If the new size is larger, the
value of the newly allocated portion of the object is indeterminate. If ptr
is a null pointer, the realloc function behaves like the malloc function for
the specified size. Otherwise, if ptr does not match a pointer earlier
returned by the calloc , malloc , or realloc function, or if the space has
been deallocated by a call to the free or realloc function, the behavior is
undefined. If the space cannot be allocated, the object pointed to by ptr
is unchanged. If size is zero and ptr is not a null pointer, the object it
points to is freed.

Returns

The realloc function returns either a null pointer or a pointer to the
possibly moved allocated space.


4.10.4 Communication with the environment


4.10.4.1 The abort function

Synopsis

#include
void abort(void);

Description

The abort function causes abnormal program termination to occur, unless
the signal SIGABRT is being caught and the signal handler does not return.
Whether open output streams are flushed or open streams closed or temporary
files removed is implementation-defined. An implementation-defined form of
the status unsuccessful termination is returned to the host environment by
means of the function call raise(SIGABRT) .

Returns

The abort function cannot return to its caller.

4.10.4.2 The atexit function


Synopsis


#include
int atexit(void (*func)(void));



Description

The atexit function registers the function pointed to by func , to be
called without arguments at normal program termination.

"Implementation limits"

The implementation shall support the registration of at least 32
functions.

Returns


The atexit function returns zero if the registration succeeds, nonzero if
it fails.

Forward references: the exit function ($4.10.4.3).

4.10.4.3 The exit function


Synopsis


#include
void exit(int status);



Description

The exit function causes normal program termination to occur. If more
than one call to the exit function is executed by a program, the behavior is
undefined.
First, all functions registered by the atexit function are called, in the
reverse order of their registration./115/
Next, all open output streams are flushed, all open streams are closed,
and all files created by the tmpfile function are removed.
Finally, control is returned to the host environment. If the value of
status is zero or EXIT_SUCCESS , an implementation-defined form of the
status successful termination is returned. If the value of status is
EXIT_FAILURE , an implementation-defined form of the status unsuccessful
termination is returned. Otherwise the status returned is
implementation-defined.

Returns

The exit function cannot return to its caller.

4.10.4.4 The getenv function


Synopsis


#include
char *getenv(const char *name);



Description

The getenv function searches an environment list ,provided by the host
environment, for a string that matches the string pointed to by name . The
set of environment names and the method for altering the environment list
are implementation-defined.
The implementation shall behave as if no library function calls the
getenv function.

Returns

The getenv function returns a pointer to a string associated with the
matched list member. The array pointed to shall not be modified by the
program, but may be overwritten by a subsequent call to the getenv function.
If the specified name cannot be found, a null pointer is returned.

4.10.4.5 The system function


Synopsis


#include
int system(const char *string);



Description

The system function passes the string pointed to by string to the host
environment to be executed by a command processor in an
implementation-defined manner. A null pointer may be used for string to
inquire whether a command processor exists.

Returns

If the argument is a null pointer, the system function returns nonzero
only if a command processor is available. If the argument is not a null
pointer, the system function returns an implementation-defined value.

4.10.5 Searching and sorting utilities


4.10.5.1 The bsearch function


Synopsis


#include
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));



Description

The bsearch function searches an array of nmemb objects, the initial
member of which is pointed to by base , for a member that matches the object
pointed to by key . The size of each member of the array is specified by
size .
The contents of the array shall be in ascending sorted order according to
a comparison function pointed to by compar ,/116/ induces which is called
with two arguments that point to the key object and to an array member, in
that order. The function shall return an integer less than, equal to, or
greater than zero if the key object is considered, respectively, to be less
than, to match, or to be greater than the array member.

Returns

The bsearch function returns a pointer to a matching member of the array,
or a null pointer if no match is found. If two members compare as equal,
which member is matched is unspecified.

4.10.5.2 The qsort function


Synopsis


#include
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));




Description

The qsort function sorts an array of nmemb objects, the initial member of
which is pointed to by base . The size of each object is specified by size
.
The contents of the array are sorted in ascending order according to a
comparison function pointed to by compar , which is called with two
arguments that point to the objects being compared. The function shall
return an integer less than, equal to, or greater than zero if the first
argument is considered to be respectively less than, equal to, or greater
than the second.
If two members compare as equal, their order in the sorted array is
unspecified.

Returns

The qsort function returns no value.

4.10.6 Integer arithmetic functions


4.10.6.1 The abs function


Synopsis


#include
int abs(int j);



Description

The abs function computes the absolute value of an integer j . If the
result cannot be represented, the behavior is undefined./117/

Returns

The abs function returns the absolute value.

4.10.6.2 The div function


Synopsis


#include
div_t div(int numer, int denom);



Description

The div function computes the quotient and remainder of the division of
the numerator numer by the denominator denom . If the division is inexact,
the sign of the resulting quotient is that of the algebraic quotient, and
the magnitude of the resulting quotient is the largest integer less than the
magnitude of the algebraic quotient. If the result cannot be represented,
the behavior is undefined; otherwise, quot * denom + rem shall equal numer .


Returns


The div function returns a structure of type div_t , comprising both the
quotient and the remainder. The structure shall contain the following
members, in either order.

int quot; /* quotient */
int rem; /* remainder */



4.10.6.3 The labs function


Synopsis


#include
long int labs(long int j);



Description

The labs function is similar to the abs function, except that the
argument and the returned value each have type long int .

4.10.6.4 The ldiv function


Synopsis


#include
ldiv_t ldiv(long int numer, long int denom);



Description

The ldiv function is similar to the div function, except that the
arguments and the members of the returned structure (which has type ldiv_t )
all have type long int .

4.10.7 Multibyte character functions

The behavior of the multibyte character functions is affected by the
LC_CTYPE category of the current locale. For a state-dependent encoding,
each function is placed into its initial state by a call for which its
character pointer argument, s , is a null pointer. Subsequent calls with s
as other than a null pointer cause the internal state of the function to be
altered as necessary. A call with s as a null pointer causes these
functions to return a nonzero value if encodings have state dependency, and
zero otherwise. After the LC_CTYPE category is changed, the shift state of
these functions is indeterminate.

4.10.7.1 The mblen function


Synopsis


#include
int mblen(const char *s, size_t n);



Description

If s is not a null pointer, the mblen function determines the number of
bytes comprising the multibyte character pointed to by s . Except that the
shift state of the mbtowc function is not affected, it is equivalent to

mbtowc((wchar_t *)0, s, n);


The implementation shall behave as if no library function calls the mblen
function.

Returns

If s is a null pointer, the mblen function returns a nonzero or zero
value, if multibyte character encodings, respectively, do or do not have
state-dependent encodings. If s is not a null pointer, the mblen function
either returns 0 (if s points to the null character), or returns the number
of bytes that comprise the multibyte character (if the next n or fewer bytes
form a valid multibyte character), or returns -1 (if they do not form a
valid multibyte character).

Forward references: the mbtowc function ($4.10.7.2).

4.10.7.2 The mbtowc function


Synopsis


#include
int mbtowc(wchar_t *pwc, const char *s, size_t n);



Description

If s is not a null pointer, the mbtowc function determines the number of
bytes that comprise the multibyte character pointed to by s . It then
determines the code for value of type wchar_t that corresponds to that
multibyte character. (The value of the code corresponding to the null
character is zero.) If the multibyte character is valid and pwc is not a
null pointer, the mbtowc function stores the code in the object pointed to
by pwc . At most n bytes of the array pointed to by s will be examined.
The implementation shall behave as if no library function calls the
mbtowc function.

Returns
If s is a null pointer, the mbtowc function returns a nonzero or zero value,
if multibyte character encodings, respectively, do or do not have
state-dependent encodings. If s is not a null pointer, the mbtowc function
either returns 0 (if s points to the null character), or returns the number
of bytes that comprise the converted multibyte character (if the next n or
fewer bytes form a valid multibyte character), or returns -1 (if they do not
form a valid multibyte character).
In no case will the value returned be greater than n or the value of the
MB_CUR_MAX macro.

4.10.7.3 The wctomb function


Synopsis


#include
int wctomb(char *s, wchar_t wchar);




Description

The wctomb function determines the number of bytes needed to represent
the multibyte character corresponding to the code whose value is wchar
(including any change in shift state). It stores the multibyte character
representation in the array object pointed to by s (if s is not a null
pointer). At most MB_CUR_MAX characters are stored. If the value of wchar
is zero, the wctomb function is left in the initial shift state.
The implementation shall behave as if no library function calls the
wctomb function.

Returns

If s is a null pointer, the wctomb function returns a nonzero or zero
value, if multibyte character encodings, respectively, do or do not have
state-dependent encodings. If s is not a null pointer, the wctomb function
returns -1 if the value of wchar does not correspond to a valid multibyte
character, or returns the number of bytes that comprise the multibyte
character corresponding to the value of wchar .
In no case will the value returned be greater than the value of the
MB_CUR_MAX macro.

4.10.8 Multibyte string functions

The behavior of the multibyte string functions is affected by the
LC_CTYPE category of the current locale.

4.10.8.1 The mbstowcs function


Synopsis


#include
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n);



Description

The mbstowcs function converts a sequence of multibyte characters that
begins in the initial shift state from the array pointed to by s into a
sequence of corresponding codes and stores not more than n codes into the
array pointed to by pwcs . No multibyte characters that follow a null
character (which is converted into a code with value zero) will be examined
or converted. Each multibyte character is converted as if by a call to the
mbtowc function, except that the shift state of the mbtowc function is not
affected.
No more than n elements will be modified in the array pointed to by pwcs
. If copying takes place between objects that overlap, the behavior is
undefined.

Returns

If an invalid multibyte character is encountered, the mbstowcs function
returns (size_t)-1 . Otherwise, the mbstowcs function returns the number of
array elements modified, not including a terminating zero code, if any.rN

4.10.8.2 The wcstombs function


Synopsis


#include
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n);



Description

The wcstombs function converts a sequence of codes that correspond to
multibyte characters from the array pointed to by pwcs into a sequence of
multibyte characters that begins in the initial shift state and stores these
multibyte characters into the array pointed to by s , stopping if a
multibyte character would exceed the limit of n total bytes or if a null
character is stored. Each code is converted as if by a call to the wctomb
function, except that the shift state of the wctomb function is not
affected.
No more than n bytes will be modified in the array pointed to by s . If
copying takes place between objects that overlap, the behavior is undefined.


Returns

If a code is encountered that does not correspond to a valid multibyte
character, the wcstombs function returns (size_t)-1 . Otherwise, the
wcstombs function returns the number of bytes modified, not including a
terminating null character, if any.rN


4.11 STRING HANDLING


4.11.1 String function conventions

The header declares one type and several functions, and
defines one macro useful for manipulating arrays of character type and other
objects treated as arrays of character type./119/ The type is size_t and
the macro is NULL (both described in $4.1.5). Various methods are used for
determining the lengths of the arrays, but in all cases a char * or void *
argument points to the initial (lowest addressed) character of the array.
If an array is accessed beyond the end of an object, the behavior is
undefined.

4.11.2 Copying functions


4.11.2.1 The memcpy function


Synopsis


#include
void *memcpy(void *s1, const void *s2, size_t n);



Description

The memcpy function copies n characters from the object pointed to by s2
into the object pointed to by s1 . If copying takes place between objects
that overlap, the behavior is undefined.

Returns

The memcpy function returns the value of s1 .

4.11.2.2 The memmove function


Synopsis


#include
void *memmove(void *s1, const void *s2, size_t n);



Description

The memmove function copies n characters from the object pointed to by s2
into the object pointed to by s1 . Copying takes place as if the n
characters from the object pointed to by s2 are first copied into a
temporary array of n characters that does not overlap the objects pointed to
by s1 and s2 , and then the n characters from the temporary array are copied
into the object pointed to by s1 .

Returns

The memmove function returns the value of s1 .

4.11.2.3 The strcpy function


Synopsis


#include
char *strcpy(char *s1, const char *s2);



Description

The strcpy function copies the string pointed to by s2 (including the
terminating null character) into the array pointed to by s1 . If copying
takes place between objects that overlap, the behavior is undefined.

Returns

The strcpy function returns the value of s1 .

4.11.2.4 The strncpy function


Synopsis


#include
char *strncpy(char *s1, const char *s2, size_t n);



Description

The strncpy function copies not more than n characters (characters that
follow a null character are not copied) from the array pointed to by s2 to
the array pointed to by s1 ./120/ If copying takes place between objects
that overlap, the behavior is undefined.
If the array pointed to by s2 is a string that is shorter than n
characters, null characters are appended to the copy in the array pointed to
by s1 , until n characters in all have been written.

Returns

The strncpy function returns the value of s1 .

4.11.3 Concatenation functions


4.11.3.1 The strcat function


Synopsis


#include
char *strcat(char *s1, const char *s2);



Description

The strcat function appends a copy of the string pointed to by s2
(including the terminating null character) to the end of the string pointed
to by s1 . The initial character of s2 overwrites the null character at the
end of s1 . If copying takes place between objects that overlap, the
behavior is undefined.

Returns

The strcat function returns the value of s1 .

4.11.3.2 The strncat function


Synopsis


#include
char *strncat(char *s1, const char *s2, size_t n);



Description

The strncat function appends not more than n characters (a null character
and characters that follow it are not appended) from the array pointed to by
s2 to the end of the string pointed to by s1 . The initial character of s2
overwrites the null character at the end of s1 . A terminating null
character is always appended to the result./121/ If copying takes place
between objects that overlap, the behavior is undefined.

Returns

The strncat function returns the value of s1 .

Forward references: the strlen function ($4.11.6.3).

4.11.4 Comparison functions

The sign of a nonzero value returned by the comparison functions is
determined by the sign of the difference between the values of the first
pair of characters (both interpreted as unsigned char ) that differ in the
objects being compared.

4.11.4.1 The memcmp function


Synopsis


#include
int memcmp(const void *s1, const void *s2, size_t n);



Description

The memcmp function compares the first n characters of the object pointed
to by s1 to the first n characters of the object pointed to by s2 ./122/

Returns

The memcmp function returns an integer greater than, equal to, or less
than zero, according as the object pointed to by s1 is greater than, equal
to, or less than the object pointed to by s2 .

4.11.4.2 The strcmp function


Synopsis


#include
int strcmp(const char *s1, const char *s2);



Description

The strcmp function compares the string pointed to by s1 to the string
pointed to by s2 .

Returns

The strcmp function returns an integer greater than, equal to, or less
than zero, according as the string pointed to by s1 is greater than, equal
to, or less than the string pointed to by s2 .

4.11.4.3 The strcoll function


Synopsis


#include
int strcoll(const char *s1, const char *s2);



Description
The strcoll function compares the string pointed to by s1 to the string
pointed to by s2 , both interpreted as appropriate to the LC_COLLATE
category of the current locale.

Returns

The strcoll function returns an integer greater than, equal to, or less
than zero, according as the string pointed to by s1 is greater than, equal
to, or less than the string pointed to by s2 when both are interpreted as
appropriate to the current locale.

4.11.4.4 The strncmp function


Synopsis


#include
int strncmp(const char *s1, const char *s2, size_t n);



Description

The strncmp function compares not more than n characters (characters that
follow a null character are not compared) from the array pointed to by s1 to
the array pointed to by s2 .

Returns

The strncmp function returns an integer greater than, equal to, or less
than zero, according as the possibly null-terminated array pointed to by s1
is greater than, equal to, or less than the possibly null-terminated array
pointed to by s2 .

4.11.4.5 The strxfrm function


Synopsis


#include
size_t strxfrm(char *s1, const char *s2, size_t n);



Description

The strxfrm function transforms the string pointed to by s2 and places
the resulting string into the array pointed to by s1 . The transformation
is such that if the strcmp function is applied to two transformed strings,
it returns a value greater than, equal to, or less than zero, corresponding
to the result of the strcoll function applied to the same two original
strings. No more than n characters are placed into the resulting array
pointed to by s1 , including the terminating null character. If n is zero,
s1 is permitted to be a null pointer. If copying takes place between
objects that overlap, the behavior is undefined.

Returns

The strxfrm function returns the length of the transformed string (not
including the terminating null character). If the value returned is n or
more, the contents of the array pointed to by s1 are indeterminate.

Example

The value of the following expression is the size of the array needed to
hold the transformation of the string pointed to by s .

1 + strxfrm(NULL, s, 0)



4.11.5 Search functions


4.11.5.1 The memchr function


Synopsis


#include
void *memchr(const void *s, int c, size_t n);



Description

The memchr function locates the first occurrence of c (converted to an
unsigned char ) in the initial n characters (each interpreted as unsigned
char ) of the object pointed to by s .

Returns

The memchr function returns a pointer to the located character, or a null
pointer if the character does not occur in the object.

4.11.5.2 The strchr function


Synopsis


#include
char *strchr(const char *s, int c);



Description

The strchr function locates the first occurrence of c (converted to a
char ) in the string pointed to by s . The terminating null character is
considered to be part of the string.

Returns

The strchr function returns a pointer to the located character, or a null
pointer if the character does not occur in the string.

4.11.5.3 The strcspn function


Synopsis


#include
size_t strcspn(const char *s1, const char *s2);



Description

The strcspn function computes the length of the maximum initial segment
of the string pointed to by s1 which consists entirely of characters not
from the string pointed to by s2 .

Returns

The strcspn function returns the length of the segment.

4.11.5.4 The strpbrk function


Synopsis



#include
char *strpbrk(const char *s1, const char *s2);



Description


The strpbrk function locates the first occurrence in the string pointed
to by s1 of any character from the string pointed to by s2 .

Returns

The strpbrk function returns a pointer to the character, or a null
pointer if no character from s2 occurs in s1 .

4.11.5.5 The strrchr function


Synopsis


#include
char *strrchr(const char *s, int c);



Description

The strrchr function locates the last occurrence of c (converted to a
char ) in the string pointed to by s . The terminating null character is
considered to be part of the string.

Returns

The strrchr function returns a pointer to the character, or a null
pointer if c does not occur in the string.

4.11.5.6 The strspn function


Synopsis


#include
size_t strspn(const char *s1, const char *s2);



Description

The strspn function computes the length of the maximum initial segment of
the string pointed to by s1 which consists entirely of characters from the
string pointed to by s2 .

Returns

The strspn function returns the length of the segment.

4.11.5.7 The strstr function


Synopsis


#include
char *strstr(const char *s1, const char *s2);



Description

The strstr function locates the first occurrence in the string pointed to
by s1 of the sequence of characters (excluding the terminating null
character) in the string pointed to by s2

Returns

The strstr function returns a pointer to the located string, or a null
pointer if the string is not found. If s2 points to a string with zero
length, the function returns s1 .

4.11.5.8 The strtok function


Synopsis


#include
char *strtok(char *s1, const char *s2);



Description

A sequence of calls to the strtok function breaks the string pointed to
by s1 into a sequence of tokens, each of which is delimited by a character
from the string pointed to by s2 . The first call in the sequence has s1 as
its first argument, and is followed by calls with a null pointer as their
first argument. The separator string pointed to by s2 may be different from
call to call.
The first call in the sequence searches the string pointed to by s1 for
the first character that is not contained in the current separator string
pointed to by s2 . If no such character is found, then there are no tokens
in the string pointed to by s1 and the strtok function returns a null
pointer. If such a character is found, it is the start of the first token.

The strtok function then searches from there for a character that is
contained in the current separator string. If no such character is found,
the current token extends to the end of the string pointed to by s1 , and
subsequent searches for a token will return a null pointer. If such a
character is found, it is overwritten by a null character, which terminates
the current token. The strtok function saves a pointer to the following
character, from which the next search for a token will start.
Each subsequent call, with a null pointer as the value of the first
argument, starts searching from the saved pointer and behaves as described
above.
The implementation shall behave as if no library function calls the
strtok function.

Returns

The strtok function returns a pointer to the first character of a token,
or a null pointer if there is no token.

Example


#include
static char str[] = "?a???b,,,#c";
char *t;


t = strtok(str, "?"); /* t points to the token "a" */
t = strtok(NULL, ","); /* t points to the token "??b" */
t = strtok(NULL, "#,"); /* t points to the token "c" */
t = strtok(NULL, "?"); /* t is a null pointer */



4.11.6 Miscellaneous functions


4.11.6.1 The memset function


Synopsis


#include
void *memset(void *s, int c, size_t n);



Description

The memset function copies the value of c (converted to an unsigned char
) into each of the first n characters of the object pointed to by s .

Returns

The memset function returns the value of s .

4.11.6.2 The strerror function


Synopsis


#include
char *strerror(int errnum);



Description

The strerror function maps the error number in errnum to an error message
string.
The implementation shall behave as if no library function calls the
strerror function.

Returns

The strerror function returns a pointer to the string, the contents of
which are implementation-defined. The array pointed to shall not be
modified by the program, but may be overwritten by a subsequent call to the
strerror function.

4.11.6.3 The strlen function


Synopsis


#include
size_t strlen(const char *s);



Description

The strlen function computes the length of the string pointed to by s .

Returns

The strlen function returns the number of characters that precede the
terminating null character.

4.12 DATE AND TIME


4.12.1 Components of time

The header defines two macros, and declares four types and
several functions for manipulating time. Many functions deal with a
calendar time that represents the current date (according to the Gregorian
calendar) and time. Some functions deal with local time ,which is the
calendar time expressed for some specific time zone, and with Daylight
Saving Time ,which is a temporary change in the algorithm for determining
local time. The local time zone and Daylight Saving Time are
implementation-defined.
The macros defined are NULL (described in $4.1.5); and

CLK_TCK

which is the number per second of the value returned by the clock function.

The types declared are size_t (described in $4.1.5);

clock_t

and

time_t

which are arithmetic types capable of representing times; and

struct tm

which holds the components of a calendar time, called the broken-down time
.The structure shall contain at least the following members, in any order.
The semantics of the members and their normal ranges are expressed in the
comments./123/

int tm_sec; /* seconds after the minute --- [0, 60] */
int tm_min; /* minutes after the hour --- [0, 59] */
int tm_hour; /* hours since midnight --- [0, 23] */
int tm_mday; /* day of the month --- [1, 31] */
int tm_mon; /* months since January --- [0, 11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday --- [0, 6] */
int tm_yday; /* days since January 1 --- [0, 365] */
int tm_isdst; /* Daylight Saving Time flag */

The value of tm_isdst is positive if Daylight Saving Time is in effect, zero
if Daylight Saving Time is not in effect, and negative if the information is
not available.

4.12.2 Time manipulation functions


4.12.2.1 The clock function


Synopsis


#include
clock_t clock(void);



Description

The clock function determines the processor time used.

Returns

The clock function returns the implementation's best approximation to the
processor time used by the program since the beginning of an
implementation-defined era related only to the program invocation. To
determine the time in seconds, the value returned by the clock function
should be divided by the value of the macro CLK_TCK . If the processor time
used is not available or its value cannot be represented, the function
returns the value (clock_t)-1 .

4.12.2.2 The difftime function


Synopsis


#include
double difftime(time_t time1, time_t time0);



Description

The difftime function computes the difference between two calendar times:
time1 - time0 .

Returns

The difftime function returns the difference expressed in seconds as a
double .

4.12.2.3 The mktime function


Synopsis


#include
time_t mktime(struct tm *timeptr);



Description

The mktime function converts the broken-down time, expressed as local
time, in the structure pointed to by timeptr into a calendar time value with
the same encoding as that of the values returned by the time function. The
original values of the tm_wday and tm_yday components of the structure are
ignored, and the original values of the other components are not restricted
to the ranges indicated above./124/ On successful completion, the values
of the tm_wday and tm_yday components of the structure are set
appropriately, and the other components are set to represent the specified
calendar time, but with their values forced to the ranges indicated above;
the final value of tm_mday is not set until tm_mon and tm_year are

determined.

Returns

The mktime function returns the specified calendar time encoded as a
value of type time_t . If the calendar time cannot be represented, the
function returns the value (time_t)-1 .

Example

What day of the week is July 4, 2001?


#include
#include
static const char *const wday[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "-unknown-"
};
struct tm time_str;



time_str.tm_year = 2001 - 1900;
time_str.tm_mon = 7 - 1;
time_str.tm_mday = 4;
time_str.tm_hour = 0;
time_str.tm_min = 0;
time_str.tm_sec = 1;
time_str.tm_isdst = -1;
if (mktime(&time_str) == -1)
time_str.tm_wday = 7;
printf("%s\n", wday[time_str.tm_wday]);



4.12.2.4 The time function


Synopsis


#include
time_t time(time_t *timer);



Description

The time function determines the current calendar time. The encoding of
the value is unspecified.

Returns

The time function returns the implementation's best approximation to the
current calendar time. The value (time_t)-1 is returned if the calendar
time is not available. If timer is not a null pointer, the return value is
also assigned to the object it points to.

4.12.3 Time conversion functions

Except for the strftime function, these functions return values in one of
two static objects: a broken-down time structure and an array of char .
Execution of any of the functions may overwrite the information returned in
either of these objects by any of the other functions. The implementation
shall behave as if no other library functions call these functions.


4.12.3.1 The asctime function


Synopsis


#include
char *asctime(const struct tm *timeptr);



Description

The asctime function converts the broken-down time in the structure
pointed to by timeptr into a string in the form

Sun Sep 16 01:03:52 1973\n\0

using the equivalent of the following algorithm.

char *asctime(const struct tm *timeptr)
{
static const char wday_name[7][3] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[12][3] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];



sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}



Returns

The asctime function returns a pointer to the string.

4.12.3.2 The ctime function


Synopsis


#include
char *ctime(const time_t *timer);



Description

The ctime function converts the calendar time pointed to by timer to
local time in the form of a string. It is equivalent to

asctime(localtime(timer))




Returns

The ctime function returns the pointer returned by the asctime function
with that broken-down time as argument.

Forward references: the localtime function ($4.12.3.4).

4.12.3.3 The gmtime function


Synopsis


#include
struct tm *gmtime(const time_t *timer);



Description

The gmtime function converts the calendar time pointed to by timer into a
broken-down time, expressed as Coordinated Universal Time (UTC).

Returns

The gmtime function returns a pointer to that object, or a null pointer
if UTC is not available.

4.12.3.4 The localtime function


Synopsis


#include
struct tm *localtime(const time_t *timer);



Description

The localtime function converts the calendar time pointed to by timer
into a broken-down time, expressed as local time.

Returns

The localtime function returns a pointer to that object.

4.12.3.5 The strftime function


Synopsis


#include
size_t strftime(char *s, size_t maxsize,
const char *format, const struct tm *timeptr);



Description

The strftime function places characters into the array pointed to by s as

controlled by the string pointed to by format . The format shall be a
multibyte character sequence, beginning and ending in its initial shift
state. The format string consists of zero or more conversion specifications
and ordinary multibyte characters. A conversion specification consists of a
% character followed by a character that determines the conversion
specification's behavior. All ordinary multibyte characters (including the
terminating null character) are copied unchanged into the array. If copying
takes place between objects that overlap, the behavior is undefined. No
more than maxsize characters are placed into the array. Each conversion
specification is replaced by appropriate characters as described in the
following list. The appropriate characters are determined by the program's
locale and by the values contained in the structure pointed to by timeptr .

is replaced by the locale's abbreviated weekday name. is replaced by the
locale's full weekday name. is replaced by the locale's abbreviated month
name. is replaced by the locale's full month name. is replaced by the
locale's appropriate date and time representation. is replaced by the day
of the month as a decimal number ( 01 - 31 ). is replaced by the hour
(24-hour clock) as a decimal number ( 00 - 23 ). is replaced by the hour
(12-hour clock) as a decimal number ( 01 - 12 ). is replaced by the day of
the year as a decimal number ( 001 - 366 ). is replaced by the month as a
decimal number ( 01 - 12 ). is replaced by the minute as a decimal number (
00 - 59 ). is replaced by the locale's equivalent of either AM or PM . is
replaced by the second as a decimal number ( 00 - 60 ). is replaced by the
week number of the year (Sunday as the first day of the week) as a decimal
number ( 00 - 53 ). is replaced by the weekday as a decimal number [ 0
(Sunday)- 6 ]. is replaced by the week number of the year (Monday as the
first day of the week) as a decimal number ( 00 - 53 ). is replaced by the
locale's appropriate date representation. is replaced by the locale's
appropriate time representation. is replaced by the year without century as
a decimal number ( 00 - 99 ). is replaced by the year with century as a
decimal number. is replaced by the time zone name, or by no characters if
no time zone is determinable. is replaced by % .
If a conversion specification is not one of the above, the behavior is
undefined.

Returns

If the total number of resulting characters including the terminating
null character is not more than maxsize , the strftime function returns the
number of characters placed into the array pointed to by s not including the
terminating null character. Otherwise, zero is returned and the contents of
the array are indeterminate.

4.13 FUTURE LIBRARY DIRECTIONS

The following names are grouped under individual headers for convenience.
All external names described below are reserved no matter what headers are
included by the program.

4.13.1 Errors

Macros that begin with E and a digit or E and an upper-case letter
(followed by any combination of digits, letters and underscore) may be added
to the declarations in the header.

4.13.2 Character handling

Function names that begin with either is or to , and a lower-case letter
(followed by any combination of digits, letters and underscore) may be added
to the declarations in the header.

4.13.3 Localization

Macros that begin with LC_ and an upper-case letter (followed by any
combination of digits, letters and underscore) may be added to the

definitions in the header.

4.13.4 Mathematics

The names of all existing functions declared in the header,
suffixed with f or l , are reserved respectively for corresponding functions
with float and long double arguments and return values.

4.13.5 Signal handling

Macros that begin with either SIG and an upper-case letter or SIG_ and an
upper-case letter (followed by any combination of digits, letters and
underscore) may be added to the definitions in the header.

4.13.6 Input/output

Lower-case letters may be added to the conversion specifiers in fprintf
and fscanf . Other characters may be used in extensions.

4.13.7 General utilities

Function names that begin with str and a lower-case letter (followed by
any combination of digits, letters and underscore) may be added to the
declarations in the header.

4.13.8 String handling

Function names that begin with str , mem , or wcs and a lower-case letter
(followed by any combination of digits, letters and underscore) may be added
to the declarations in the header. header.



  3 Responses to “Category : C Source Code
Archive   : ANSI-C.ZIP
Filename : LIB

  1. Very nice! Thank you for this wonderful archive. I wonder why I found it only now. Long live the BBS file archives!

  2. This is so awesome! 😀 I’d be cool if you could download an entire archive of this at once, though.

  3. But one thing that puzzles me is the “mtswslnkmcjklsdlsbdmMICROSOFT” string. There is an article about it here. It is definitely worth a read: http://www.os2museum.com/wp/mtswslnk/