static wchar_t wstr[] = L" X Yabc Z W";
the seven calls
fprintf(stdout, "|1234567890123|\n");
fprintf(stdout, "|%13ls|\n", wstr);
fprintf(stdout, "|%-13.9ls|\n", wstr);
fprintf(stdout, "|%13.10ls|\n", wstr);
fprintf(stdout, "|%13.11ls|\n", wstr);
fprintf(stdout, "|%13.15ls|\n", &wstr[2]);
fprintf(stdout, "|%13lc|\n", (wint_t) wstr[5]);
will print the following seven lines:
|1234567890123|
| X Yabc Z W|
| X Yabc Z |
| X Yabc Z|
| X Yabc Z W|
| abc Z W|
| Z|
Forward references: conversion state (7.24.6), the wcrtomb function (<IP_ADDRESS>.3).
<IP_ADDRESS> [The fscanf function]
1 Synopsis
#include <stdio.h>
int fscanf(FILE * restrict stream,
const char * restrict format, ...);
Description
2 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.
3 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 (neither % nor a white-space character), 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 greater than zero that specifies the maximum field width
(in characters).
— An optional length modifier that specifies the size of the receiving object.
— A conversion specifier character that specifies the type of conversion to be applied.
4 The fscanf function executes each directive of the format in turn. If a directive fails, as
detailed below, the function returns. Failures are described as input failures (due to the
occurrence of an encoding error or the unavailability of input characters), or matching
failures (due to inappropriate input).
5 A directive composed of white-space character(s) is executed by reading input up to the
first non-white-space character (which remains unread), or until no more characters can
be read.
6 A directive that is an ordinary multibyte character is executed by reading the next
characters of the stream. If any of those characters differ from the ones composing the
directive, the directive fails and the differing and subsequent characters remain unread.
Similarly, if end-of-file, an encoding error, or a read error prevents a character from being
read, the directive fails.
7 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:
8 Input white-space characters (as specified by the isspace function) are skipped, unless
the specification includes a [, c, or n specifier.[250]
Footnote 250) These white-space characters are not counted against a specified field width.
9 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 which does not exceed
any specified field width and which is, or is a prefix of, a matching input sequence.[251]
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
end-of-file, an encoding error, or a read error prevented input from the stream, in which
case it is an input failure.
Footnote 251) fscanf pushes back at most one input character onto the input stream. Therefore, some sequences
that are acceptable to strtod, strtol, etc., are unacceptable to fscanf.
10 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 object, the behavior is undefined.
11 The length modifiers and their meanings are:
hh Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to signed char or unsigned char.
h Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to short int or unsigned short
int.
l (ell) Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to long int or unsigned long
int; that a following a, A, e, E, f, F, g, or G conversion specifier applies to
an argument with type pointer to double; or that a following c, s, or [
conversion specifier applies to an argument with type pointer to wchar_t.
ll (ell-ell) Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to long long int or unsigned
long long int.
j Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to intmax_t or uintmax_t.
z Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to size_t or the corresponding signed
integer type.
t Specifies that a following d, i, o, u, x, X, or n conversion specifier applies
to an argument with type pointer to ptrdiff_t or the corresponding
unsigned integer type.
L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier
applies to an argument with type pointer to long double.
If a length modifier appears with any conversion specifier other than as specified above,
the behavior is undefined.
12 The conversion specifiers and their meanings are:
d 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
signed integer.
i 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 signed
integer.
o 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.
u 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.
x 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.
a,e,f,g Matches an optionally signed floating-point number, infinity, or NaN, whose
format is the same as expected for the subject sequence of the strtod
function. The corresponding argument shall be a pointer to floating.
c Matches a sequence of characters of exactly the number specified by the field
width (1 if no field width is present in the directive).[252]
If no l length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence. No null character is added.
If an l length modifier is present, the input shall be a sequence of multibyte
characters that begins in the initial shift state. Each multibyte character in the
sequence is converted to a wide character as if by a call to the mbrtowc
function, with the conversion state described by an mbstate_t object
initialized to zero before the first multibyte character is converted. The
corresponding argument shall be a pointer to the initial element of an array of
wchar_t large enough to accept the resulting sequence of wide characters.
No null wide character is added.
s Matches a sequence of non-white-space characters.[252]
If no l length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence and a terminating null character, which will be added automatically.
If an l length modifier is present, the input shall be a sequence of multibyte
characters that begins in the initial shift state. Each multibyte character is
converted to a wide character as if by a call to the mbrtowc function, with
the conversion state described by an mbstate_t object initialized to zero
before the first multibyte character is converted. The corresponding argument
shall be a pointer to the initial element of an array of wchar_t large enough
to accept the sequence and the terminating null wide character, which will be
added automatically.
[ Matches a nonempty sequence of characters from a set of expected characters
(the scanset).[252]
If no l length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence and a terminating null character, which will be added automatically.
If an l length modifier is present, the input shall be a sequence of multibyte
characters that begins in the initial shift state. Each multibyte character is
converted to a wide character as if by a call to the mbrtowc function, with
the conversion state described by an mbstate_t object initialized to zero
before the first multibyte character is converted. The corresponding argument
shall be a pointer to the initial element of an array of wchar_t large enough
to accept the sequence and the terminating null wide 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) compose 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. If the conversion specifier begins with [] or [^], the right
bracket character is in the scanlist and the next following right bracket
character is the matching right bracket that ends the specification; otherwise
the first following right bracket character is the one 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.
p 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 input item is converted to a pointer value in an
implementation-defined manner. If the input item is a value converted earlier
during the same program execution, the pointer that results shall compare
equal to that value; otherwise the behavior of the %p conversion is undefined.
n No input is consumed. The corresponding argument shall be a pointer to
signed 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. No argument is converted,
but one is consumed. If the conversion specification includes an assignment-
suppressing character or a field width, the behavior is undefined.
% Matches a single % character; no conversion or assignment occurs. The
complete conversion specification shall be %%.
Footnote 252) No special provisions are made for multibyte characters in the matching rules used by the c, s, and [
conversion specifiers — the extent of the input field is determined on a byte-by-byte basis. The
resulting field is nevertheless a sequence of multibyte characters that begins in the initial shift state.
Footnote 252) No special provisions are made for multibyte characters in the matching rules used by the c, s, and [
conversion specifiers — the extent of the input field is determined on a byte-by-byte basis. The
resulting field is nevertheless a sequence of multibyte characters that begins in the initial shift state.
Footnote 252) No special provisions are made for multibyte characters in the matching rules used by the c, s, and [
conversion specifiers — the extent of the input field is determined on a byte-by-byte basis. The
resulting field is nevertheless a sequence of multibyte characters that begins in the initial shift state.
13 If a conversion specification is invalid, the behavior is undefined.[253]
Footnote 253) See ‘‘future library directions’’ (7.26.9).
14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as,
respectively, a, e, f, g, and x.
15 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
16 The fscanf function returns the value of the macro EOF if an input failure occurs
before any conversion. Otherwise, the 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.
17 EXAMPLE 1 The call:
#include <stdio.h>
/* ... */
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 to name the sequence
thompson\0.
18 EXAMPLE 2 The call:
#include <stdio.h>
/* ... */
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 will assign to name the
sequence 56\0. The next character read from the input stream will be a.
19 EXAMPLE 3 To accept repeatedly from stdin a quantity, a unit of measure, and an item name:
#include <stdio.h>
/* ... */
int count; float quant; char units[21], item[21];
do {
count = fscanf(stdin, "%f%20s of %20s", &quant, units, item);
fscanf(stdin,"%*[^\n]");
} while (!feof(stdin) && !ferror(stdin));
20 If the stdin stream contains the following lines:
2 quarts of oil
-12.8degrees Celsius
lots of luck
10.0LBS of
dirt
100ergs of energy
the execution of the above example will be analogous 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, "dirt");
count = 3;
count = 0; // "100e" fails to match "%f"
count = EOF;
21 EXAMPLE 4 In:
#include <stdio.h>
/* ... */
int d1, d2, n1, n2, i;
i = sscanf("123", "%d%n%n%d", &d1, &n1, &n2, &d2);
the value 123 is assigned to d1 and the value 3 to n1. Because %n can never get an input failure the value
of 3 is also assigned to n2. The value of d2 is not affected. The value 1 is assigned to i.
22 EXAMPLE 5 In these examples, multibyte characters do have a state-dependent encoding, and the
members of the extended character set that consist of more than one byte each consist of exactly two bytes,
the first of which is denoted here by a and the second by an uppercase letter, but are only recognized as
such when in the alternate shift state. The shift sequences are denoted by ↑ and ↓, in which the first causes
entry into the alternate shift state.
23 After the call:
#include <stdio.h>
/* ... */
char str[50];
fscanf(stdin, "a%s", str);
with the input line:
a↑ X Y↓ bc
str will contain ↑ X Y↓\0 assuming that none of the bytes of the shift sequences (or of the multibyte
characters, in the more general case) appears to be a single-byte white-space character.
24 In contrast, after the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a%ls", wstr);
with the same input line, wstr will contain the two wide characters that correspond to X and Y and a
terminating null wide character.
25 However, the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a↑ X↓%ls", wstr);
with the same input line will return zero due to a matching failure against the ↓ sequence in the format
string.
26 Assuming that the first byte of the multibyte character X is the same as the first byte of the multibyte
character Y, after the call:
#include <stdio.h>
#include <stddef.h>
/* ... */
wchar_t wstr[50];
fscanf(stdin, "a↑ Y↓%ls", wstr);
with the same input line, zero will again be returned, but stdin will be left with a partially consumed
multibyte character.
Forward references: the strtod, strtof, and strtold functions (<IP_ADDRESS>), the
strtol, strtoll, strtoul, and strtoull functions (<IP_ADDRESS>), conversion state
(7.24.6), the wcrtomb function (<IP_ADDRESS>.3).
<IP_ADDRESS> [The printf function]
1 Synopsis
#include <stdio.h>
int printf(const char * restrict format, ...);
Description
2 The printf function is equivalent to fprintf with the argument stdout interposed
before the arguments to printf.
Returns
3 The printf function returns the number of characters transmitted, or a negative value if
an output or encoding error occurred.
<IP_ADDRESS> [The scanf function]
1 Synopsis
#include <stdio.h>
int scanf(const char * restrict format, ...);
Description
2 The scanf function is equivalent to fscanf with the argument stdin interposed
before the arguments to scanf.
Returns
3 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.
<IP_ADDRESS> [The snprintf function]
1 Synopsis
#include <stdio.h>
int snprintf(char * restrict s, size_t n,
const char * restrict format, ...);
Description
2 The snprintf function is equivalent to fprintf, except that the output is written into
an array (specified by argument s) rather than to a stream. If n is zero, nothing is written,
and s may be a null pointer. Otherwise, output characters beyond the n-1st are
discarded rather than being written to the array, and a null character is written at the end
of the characters actually written into the array. If copying takes place between objects
that overlap, the behavior is undefined.
Returns
3 The snprintf function returns the number of characters that would have been written
had n been sufficiently large, not counting the terminating null character, or a negative
value if an encoding error occurred. Thus, the null-terminated output has been
completely written if and only if the returned value is nonnegative and less than n.
<IP_ADDRESS> [The sprintf function]
1 Synopsis
#include <stdio.h>
int sprintf(char * restrict s,
const char * restrict format, ...);
Description
2 The sprintf function is equivalent to fprintf, except that the output is written into
an array (specified by the argument s) 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 value. If
copying takes place between objects that overlap, the behavior is undefined.
Returns
3 The sprintf function returns the number of characters written in the array, not
counting the terminating null character, or a negative value if an encoding error occurred.
<IP_ADDRESS> [The sscanf function]
1 Synopsis
#include <stdio.h>
int sscanf(const char * restrict s,
const char * restrict format, ...);
Description
2 The sscanf function is equivalent to fscanf, except that input is obtained from a
string (specified by the argument s) 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
3 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.
<IP_ADDRESS> [The vfprintf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vfprintf(FILE * restrict stream,
const char * restrict format,
va_list arg);
Description
2 The vfprintf function is equivalent to fprintf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vfprintf function does not invoke the
va_end macro.[254]
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vfprintf function returns the number of characters transmitted, or a negative
value if an output or encoding error occurred.
4 EXAMPLE The following shows the use of the vfprintf function in a general error-reporting routine.
#include <stdarg.h>
#include <stdio.h>
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);
}
<IP_ADDRESS> [The vfscanf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vfscanf(FILE * restrict stream,
const char * restrict format,
va_list arg);
Description
2 The vfscanf function is equivalent to fscanf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vfscanf function does not invoke the
va_end macro.[254]
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vfscanf function returns the value of the macro EOF if an input failure occurs
before any conversion. Otherwise, the vfscanf 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.
<IP_ADDRESS> [The vprintf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vprintf(const char * restrict format,
va_list arg);
Description
2 The vprintf function is equivalent to printf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vprintf function does not invoke the
va_end macro.[254]
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vprintf function returns the number of characters transmitted, or a negative value
if an output or encoding error occurred.
<IP_ADDRESS> [The vscanf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vscanf(const char * restrict format,
va_list arg);
Description
2 The vscanf function is equivalent to scanf, with the variable argument list replaced
by arg, which shall have been initialized by the va_start macro (and possibly
subsequent va_arg calls). The vscanf function does not invoke the va_end
macro.[254]
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vscanf function returns the value of the macro EOF if an input failure occurs
before any conversion. Otherwise, the vscanf 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.
<IP_ADDRESS> [The vsnprintf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsnprintf(char * restrict s, size_t n,
const char * restrict format,
va_list arg);
Description
2 The vsnprintf function is equivalent to snprintf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vsnprintf function does not invoke the
va_end macro.[254] If copying takes place between objects that overlap, the behavior is
undefined.
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vsnprintf function returns the number of characters that would have been written
had n been sufficiently large, not counting the terminating null character, or a negative
value if an encoding error occurred. Thus, the null-terminated output has been
completely written if and only if the returned value is nonnegative and less than n.
<IP_ADDRESS> [The vsprintf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsprintf(char * restrict s,
const char * restrict format,
va_list arg);
Description
2 The vsprintf function is equivalent to sprintf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vsprintf function does not invoke the
va_end macro.[254] If copying takes place between objects that overlap, the behavior is
undefined.
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vsprintf function returns the number of characters written in the array, not
counting the terminating null character, or a negative value if an encoding error occurred.
<IP_ADDRESS> [The vsscanf function]
1 Synopsis
#include <stdarg.h>
#include <stdio.h>
int vsscanf(const char * restrict s,
const char * restrict format,
va_list arg);
Description
2 The vsscanf function is equivalent to sscanf, with the variable argument list
replaced by arg, which shall have been initialized by the va_start macro (and
possibly subsequent va_arg calls). The vsscanf function does not invoke the
va_end macro.[254]
Returns
Footnote 254) As the functions vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, and
vsscanf invoke the va_arg macro, the value of arg after the return is indeterminate.
3 The vsscanf function returns the value of the macro EOF if an input failure occurs
before any conversion. Otherwise, the vsscanf 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.
7.19.7 [Character input/output functions]
<IP_ADDRESS> [The fgetc function]
1 Synopsis
#include <stdio.h>
int fgetc(FILE *stream);
Description
2 If the end-of-file indicator for the input stream pointed to by stream is not set and a
next character is present, the fgetc function obtains that character as an unsigned
char converted to an int and advances the associated file position indicator for the
stream (if defined).
Returns
3 If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-
of-file indicator for the stream is set and the fgetc function returns EOF. Otherwise, the
fgetc function returns the next character from the input stream pointed to by stream.
If a read error occurs, the error indicator for the stream is set and the fgetc function
returns EOF.[255]
Footnote 255) An end-of-file and a read error can be distinguished by use of the feof and ferror functions.
<IP_ADDRESS> [The fgets function]
1 Synopsis
#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);
Description
2 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
3 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.
<IP_ADDRESS> [The fputc function]
1 Synopsis
#include <stdio.h>
int fputc(int c, FILE *stream);
Description
2 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
3 The fputc function returns the character written. If a write error occurs, the error
indicator for the stream is set and fputc returns EOF.
<IP_ADDRESS> [The fputs function]
1 Synopsis
#include <stdio.h>
int fputs(const char * restrict s,
FILE * restrict stream);
Description
2 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
3 The fputs function returns EOF if a write error occurs; otherwise it returns a
nonnegative value.
<IP_ADDRESS> [The getc function]
1 Synopsis
#include <stdio.h>
int getc(FILE *stream);
Description
2 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
3 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.
<IP_ADDRESS> [The getchar function]
1 Synopsis
#include <stdio.h>
int getchar(void);
Description
2 The getchar function is equivalent to getc with the argument stdin.
Returns
3 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.
<IP_ADDRESS> [The gets function]
1 Synopsis
#include <stdio.h>
char *gets(char *s);
Description
2 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
3 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.
Forward references: future library directions (7.26.9).
<IP_ADDRESS> [The putc function]
1 Synopsis
#include <stdio.h>
int putc(int c, FILE *stream);
Description
2 The putc function is equivalent to fputc, except that if it is implemented as a macro, it
may evaluate stream more than once, so that argument should never be an expression
with side effects.
Returns
3 The putc function returns the character written. If a write error occurs, the error
indicator for the stream is set and putc returns EOF.
<IP_ADDRESS> [The putchar function]
1 Synopsis
#include <stdio.h>
int putchar(int c);
Description
2 The putchar function is equivalent to putc with the second argument stdout.
Returns
3 The putchar function returns the character written. If a write error occurs, the error
indicator for the stream is set and putchar returns EOF.
<IP_ADDRESS> [The puts function]
1 Synopsis
#include <stdio.h>
int puts(const char *s);
Description
2 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
3 The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative
value.
<IP_ADDRESS> [The ungetc function]
1 Synopsis
#include <stdio.h>
int ungetc(int c, FILE *stream);
Description
2 The ungetc function pushes the character specified by c (converted to an unsigned
char) back onto the input stream pointed to by stream. 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.
3 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.
4 If the value of c equals that of the macro EOF, the operation fails and the input stream is
unchanged.
5 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.[256]
Returns
Footnote 256) See ‘‘future library directions’’ (7.26.9).
6 The ungetc function returns the character pushed back after conversion, or EOF if the
operation fails.
Forward references: file positioning functions (7.19.9).
7.19.8 [Direct input/output functions]
<IP_ADDRESS> [The fread function]
1 Synopsis
#include <stdio.h>
size_t fread(void * restrict ptr,
size_t size, size_t nmemb,
FILE * restrict stream);
Description
2 The fread function reads, into the array pointed to by ptr, up to nmemb elements
whose size is specified by size, from the stream pointed to by stream. For each
object, size calls are made to the fgetc function and the results stored, in the order
read, in an array of unsigned char exactly overlaying the object. 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 element is read, its value is indeterminate.
Returns
3 The fread function returns the number of elements 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.
<IP_ADDRESS> [The fwrite function]
1 Synopsis
#include <stdio.h>
size_t fwrite(const void * restrict ptr,
size_t size, size_t nmemb,
FILE * restrict stream);
Description
2 The fwrite function writes, from the array pointed to by ptr, up to nmemb elements
whose size is specified by size, to the stream pointed to by stream. For each object,
size calls are made to the fputc function, taking the values (in order) from an array of
unsigned char exactly overlaying the object. 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
3 The fwrite function returns the number of elements successfully written, which will be
less than nmemb only if a write error is encountered. If size or nmemb is zero,
fwrite returns zero and the state of the stream remains unchanged.
7.19.9 [File positioning functions]
<IP_ADDRESS> [The fgetpos function]
1 Synopsis
#include <stdio.h>
int fgetpos(FILE * restrict stream,
fpos_t * restrict pos);
Description
2 The fgetpos function stores the current values of the parse state (if any) and file
position indicator for the stream pointed to by stream in the object pointed to by pos.
The values stored contain 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
3 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 (<IP_ADDRESS>).
<IP_ADDRESS> [The fseek function]
1 Synopsis
#include <stdio.h>
int fseek(FILE *stream, long int offset, int whence);
Description
2 The fseek function sets the file position indicator for the stream pointed to by stream.
If a read or write error occurs, the error indicator for the stream is set and fseek fails.
3 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
position is the beginning of the file if whence is SEEK_SET, the current value of the file
position indicator if SEEK_CUR, or end-of-file if SEEK_END. A binary stream need not
meaningfully support fseek calls with a whence value of SEEK_END.
4 For a text stream, either offset shall be zero, or offset shall be a value returned by
an earlier successful call to the ftell function on a stream associated with the same file
and whence shall be SEEK_SET.
5 After determining the new position, a successful call to the fseek function undoes any
effects of the ungetc function on the stream, clears the end-of-file indicator for the
stream, and then establishes the new position. After a successful fseek call, the next
operation on an update stream may be either input or output.
Returns
6 The fseek function returns nonzero only for a request that cannot be satisfied.
Forward references: the ftell function (<IP_ADDRESS>).
<IP_ADDRESS> [The fsetpos function]
1 Synopsis
#include <stdio.h>
int fsetpos(FILE *stream, const fpos_t *pos);
Description
2 The fsetpos function sets the mbstate_t object (if any) and 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 obtained from an earlier successful call to the fgetpos
function on a stream associated with the same file. If a read or write error occurs, the
error indicator for the stream is set and fsetpos fails.
3 A successful call to the fsetpos function undoes any effects of the ungetc function
on the stream, clears the end-of-file indicator for the stream, and then establishes the new
parse state and position. After a successful fsetpos call, the next operation on an
update stream may be either input or output.
Returns
4 If successful, the fsetpos function returns zero; on failure, the fsetpos function
returns nonzero and stores an implementation-defined positive value in errno.
<IP_ADDRESS> [The ftell function]
1 Synopsis
#include <stdio.h>
long int ftell(FILE *stream);
Description
2 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
3 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.
<IP_ADDRESS> [The rewind function]
1 Synopsis
#include <stdio.h>
void rewind(FILE *stream);
Description
2 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
3 The rewind function returns no value.
7.19.10 [Error-handling functions]
<IP_ADDRESS> [The clearerr function]
1 Synopsis
#include <stdio.h>
void clearerr(FILE *stream);
Description
2 The clearerr function clears the end-of-file and error indicators for the stream pointed
to by stream.
Returns
3 The clearerr function returns no value.
<IP_ADDRESS> [The feof function]
1 Synopsis
#include <stdio.h>
int feof(FILE *stream);
Description
2 The feof function tests the end-of-file indicator for the stream pointed to by stream.
Returns
3 The feof function returns nonzero if and only if the end-of-file indicator is set for
stream.
<IP_ADDRESS> [The ferror function]
1 Synopsis
#include <stdio.h>
int ferror(FILE *stream);
Description
2 The ferror function tests the error indicator for the stream pointed to by stream.
Returns
3 The ferror function returns nonzero if and only if the error indicator is set for
stream.
<IP_ADDRESS> [The perror function]
1 Synopsis
#include <stdio.h>
void perror(const char *s);
Description
2 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.
Returns
3 The perror function returns no value.
Forward references: the strerror function (<IP_ADDRESS>).
7.20 [General utilities <stdlib.h>]
1 The header <stdlib.h> declares five types and several functions of general utility, and
defines several macros.[257]
Footnote 257) See ‘‘future library directions’’ (7.26.10).
2 The types declared are size_t and wchar_t (both described in 7.17),
div_t
which is a structure type that is the type of the value returned by the div function,
ldiv_t
which is a structure type that is the type of the value returned by the ldiv function, and
lldiv_t
which is a structure type that is the type of the value returned by the lldiv function.
3 The macros defined are NULL (described in 7.17);
EXIT_FAILURE
and
EXIT_SUCCESS
which expand to integer constant expressions that can 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 integer constant expression that is the maximum value returned by
the rand function; and
MB_CUR_MAX
which expands to a positive integer expression with type size_t that is the maximum
number of bytes in a multibyte character for the extended character set specified by the
current locale (category LC_CTYPE), which is never greater than MB_LEN_MAX.
7.20.1 [Numeric conversion functions]
1 The functions atof, atoi, atol, and atoll 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.
<IP_ADDRESS> [The atof function]
1 Synopsis
#include <stdlib.h>
double atof(const char *nptr);
Description
2 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
3 The atof function returns the converted value.
Forward references: the strtod, strtof, and strtold functions (<IP_ADDRESS>).
<IP_ADDRESS> [The atoi, atol, and atoll functions]
1 Synopsis
#include <stdlib.h>
int atoi(const char *nptr);
long int atol(const char *nptr);
long long int atoll(const char *nptr);
Description
2 The atoi, atol, and atoll functions convert the initial portion of the string pointed
to by nptr to int, long int, and long long int representation, respectively.
Except for the behavior on error, they are equivalent to
atoi: (int)strtol(nptr, (char **)NULL, 10)
atol: strtol(nptr, (char **)NULL, 10)
atoll: strtoll(nptr, (char **)NULL, 10)
Returns
3 The atoi, atol, and atoll functions return the converted value.
Forward references: the strtol, strtoll, strtoul, and strtoull functions
(<IP_ADDRESS>).
<IP_ADDRESS> [The strtod, strtof, and strtold functions]
1 Synopsis
#include <stdlib.h>
double strtod(const char * restrict nptr,
char ** restrict endptr);
float strtof(const char * restrict nptr,
char ** restrict endptr);
long double strtold(const char * restrict nptr,
char ** restrict endptr);
Description
2 The strtod, strtof, and strtold functions convert the initial portion of the string
pointed to by nptr to double, float, and long double representation,
respectively. First, they decompose 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 or representing an infinity or NaN;
and a final string of one or more unrecognized characters, including the terminating null
character of the input string. Then, they attempt to convert the subject sequence to a
floating-point number, and return the result.
3 The expected form of the subject sequence is an optional plus or minus sign, then one of
the following:
— a nonempty sequence of decimal digits optionally containing a decimal-point
character, then an optional exponent part as defined in <IP_ADDRESS>;
— a 0x or 0X, then a nonempty sequence of hexadecimal digits optionally containing a
decimal-point character, then an optional binary exponent part as defined in <IP_ADDRESS>;
— INF or INFINITY, ignoring case
— NAN or NAN(n-char-sequenceopt), ignoring case in the NAN part, where:
n-char-sequence:
digit
nondigit
n-char-sequence digit
n-char-sequence nondigit
The subject sequence is defined as the longest initial subsequence of the input string,
starting with the first non-white-space character, that is of the expected form. The subject
sequence contains no characters if the input string is not of the expected form.
4 If the subject sequence has the expected form for a floating-point number, the sequence of
characters starting with the first digit or the decimal-point character (whichever occurs
decimal-point character is used in place of a period, and that if neither an exponent part
nor a decimal-point character appears in a decimal floating point number, or if a binary
exponent part does not appear in a hexadecimal floating point number, an exponent part
of the appropriate type with value zero is assumed to follow the last digit in the string. If
the subject sequence begins with a minus sign, the sequence is interpreted as negated.258)
A character sequence INF or INFINITY is interpreted as an infinity, if representable in
the return type, else like a floating constant that is too large for the range of the return
type. A character sequence NAN or NAN(n-char-sequenceopt), is interpreted as a quiet
NaN, if supported in the return type, else like a subject sequence part that does not have
the expected form; the meaning of the n-char sequences is implementation-defined.[259] A
pointer to the final string is stored in the object pointed to by endptr, provided that
endptr is not a null pointer.
Footnote 259) An implementation may use the n-char sequence to determine extra information to be represented in
the NaN’s significand.
5 If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, the
value resulting from the conversion is correctly rounded.
6 In other than the "C" locale, additional locale-specific subject sequence forms may be
accepted.
7 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.
Recommended practice
8 If the subject sequence has the hexadecimal form, FLT_RADIX is not a power of 2, and
the result is not exactly representable, the result should be one of the two numbers in the
appropriate internal format that are adjacent to the hexadecimal floating source value,
with the extra stipulation that the error should have a correct sign for the current rounding
direction.
9 If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in
<float.h>) significant digits, the result should be correctly rounded. If the subject
sequence D has the decimal form and more than DECIMAL_DIG significant digits,
consider the two bounding, adjacent decimal strings L and U, both having
DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy L ≤ D ≤ U.
The result should be one of the (equal or adjacent) values that would be obtained by
correctly rounding L and U according to the current rounding direction, with the extra
stipulation that the error with respect to D should have a correct sign for the current
rounding direction.[260]
Returns
Footnote 260) DECIMAL_DIG, defined in <float.h>, should be sufficiently large that L and U will usually round
to the same internal floating value, but if not will round to adjacent values.
10 The functions return the converted value, if any. If no conversion could be performed,
zero is returned. If the correct value is outside the range of representable values, plus or
minus HUGE_VAL, HUGE_VALF, or HUGE_VALL is returned (according to the return
type and sign of the value), and the value of the macro ERANGE is stored in errno. If
the result underflows (7.12.1), the functions return a value whose magnitude is no greater
than the smallest normalized positive number in the return type; whether errno acquires
the value ERANGE is implementation-defined.
<IP_ADDRESS> [The strtol, strtoll, strtoul, and strtoull functions]
1 Synopsis
#include <stdlib.h>
long int strtol(
const char * restrict nptr,
char ** restrict endptr,
int base);
long long int strtoll(
const char * restrict nptr,
char ** restrict endptr,
int base);
unsigned long int strtoul(
const char * restrict nptr,
char ** restrict endptr,
int base);
unsigned long long int strtoull(
const char * restrict nptr,
char ** restrict endptr,
int base);
Description
2 The strtol, strtoll, strtoul, and strtoull functions convert the initial
portion of the string pointed to by nptr to long int, long long int, unsigned
long int, and unsigned long long int representation, respectively. First,
they decompose 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, they attempt to convert the subject sequence to an
integer, and return the result.
3 If the value of base is zero, the expected form of the subject sequence is that of an
integer constant as described in <IP_ADDRESS>, optionally preceded by a plus or minus sign, but
not including an integer suffix. If the value of base is between 2 and 36 (inclusive), 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 through 35; only letters and digits 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.
4 The subject sequence is defined as the longest initial subsequence of the input string,
starting with the first non-white-space character, that is 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.
5 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 <IP_ADDRESS>. 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 (in the return type). A pointer to the final string is stored in the
object pointed to by endptr, provided that endptr is not a null pointer.
6 In other than the "C" locale, additional locale-specific subject sequence forms may be
accepted.
7 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
8 The strtol, strtoll, strtoul, and strtoull functions return the converted
value, if any. If no conversion could be performed, zero is returned. If the correct value
is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN,
LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type
and sign of the value, if any), and the value of the macro ERANGE is stored in errno.
7.20.2 [Pseudo-random sequence generation functions]
<IP_ADDRESS> [The rand function]
1 Synopsis
#include <stdlib.h>
int rand(void);
Description
2 The rand function computes a sequence of pseudo-random integers in the range 0 to
RAND_MAX.
3 The implementation shall behave as if no library function calls the rand function.
Returns
4 The rand function returns a pseudo-random integer.
Environmental limits
5 The value of the RAND_MAX macro shall be at least 32767.
<IP_ADDRESS> [The srand function]
1 Synopsis
#include <stdlib.h>
void srand(unsigned int seed);
Description
2 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.
3 The implementation shall behave as if no library function calls the srand function.
Returns
4 The srand function returns no value.
5 EXAMPLE The following functions define a portable implementation of rand and srand.
static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
next = next *<PHONE_NUMBER> + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}
7.20.3 [Memory management functions]
1 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 or an array of such objects in the space allocated
(until the space is explicitly deallocated). The lifetime of an allocated object extends
from the allocation until the deallocation. 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: either a null pointer is returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not be used to access an object.
<IP_ADDRESS> [The calloc function]
1 Synopsis
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
Description
2 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.[261]
Returns
Footnote 261) Note that this need not be the same as the representation of floating-point zero or a null pointer
constant.
3 The calloc function returns either a null pointer or a pointer to the allocated space.
<IP_ADDRESS> [The free function]
1 Synopsis
#include <stdlib.h>
void free(void *ptr);
Description
2 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
3 The free function returns no value.
<IP_ADDRESS> [The malloc function]
1 Synopsis
#include <stdlib.h>
void *malloc(size_t size);
Description
2 The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.
Returns
3 The malloc function returns either a null pointer or a pointer to the allocated space.
<IP_ADDRESS> [The realloc function]
1 Synopsis
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
2 The realloc function deallocates the old object pointed to by ptr and returns a
pointer to a new object that has the size specified by size. The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of
the new and old sizes. Any bytes in the new object beyond the size of the old object have
indeterminate values.
3 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 memory for the new
object cannot be allocated, the old object is not deallocated and its value is unchanged.
Returns
4 The realloc function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new object could not be
allocated.
7.20.4 [Communication with the environment]
<IP_ADDRESS> [The abort function]
1 Synopsis
#include <stdlib.h>
void abort(void);
Description
2 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 streams
with unwritten buffered data are flushed, open streams are closed, or temporary files are
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
3 The abort function does not return to its caller.
<IP_ADDRESS> [The atexit function]
1 Synopsis
#include <stdlib.h>
int atexit(void (*func)(void));
Description
2 The atexit function registers the function pointed to by func, to be called without
arguments at normal program termination.
Environmental limits
3 The implementation shall support the registration of at least 32 functions.
Returns
4 The atexit function returns zero if the registration succeeds, nonzero if it fails.
Forward references: the exit function (<IP_ADDRESS>).
<IP_ADDRESS> [The exit function]
1 Synopsis
#include <stdlib.h>
void exit(int status);
Description
2 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.
3 First, all functions registered by the atexit function are called, in the reverse order of
their registration,[262] except that a function is called after any previously registered
functions that had already been called at the time it was registered. If, during the call to
any such function, a call to the longjmp function is made that would terminate the call
to the registered function, the behavior is undefined.
Footnote 262) Each function is called as many times as it was registered, and in the correct order with respect to
other registered functions.
4 Next, all open streams with unwritten buffered data are flushed, all open streams are
closed, and all files created by the tmpfile function are removed.
5 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
6 The exit function cannot return to its caller.
<IP_ADDRESS> [The _Exit function]
1 Synopsis
#include <stdlib.h>
void _Exit(int status);
Description
2 The _Exit function causes normal program termination to occur and control to be
returned to the host environment. No functions registered by the atexit function or
signal handlers registered by the signal function are called. The status returned to the
host environment is determined in the same way as for the exit function (<IP_ADDRESS>).
Whether open streams with unwritten buffered data are flushed, open streams are closed,
or temporary files are removed is implementation-defined.
Returns
3 The _Exit function cannot return to its caller.
<IP_ADDRESS> [The getenv function]
1 Synopsis
#include <stdlib.h>
char *getenv(const char *name);
Description
2 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.
3 The implementation shall behave as if no library function calls the getenv function.
Returns
4 The getenv function returns a pointer to a string associated with the matched list
member. The string 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.
<IP_ADDRESS> [The system function]
1 Synopsis
#include <stdlib.h>
int system(const char *string);
Description
2 If string is a null pointer, the system function determines whether the host
environment has a command processor. If string is not a null pointer, the system
function passes the string pointed to by string to that command processor to be
executed in a manner which the implementation shall document; this might then cause the
program calling system to behave in a non-conforming manner or to terminate.
Returns
3 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, and the system
function does return, it returns an implementation-defined value.
7.20.5 [Searching and sorting utilities]
1 These utilities make use of a comparison function to search or sort arrays of unspecified
type. Where an argument declared as size_t nmemb specifies the length of the array
for a function, nmemb can have the value zero on a call to that function; the comparison
function is not called, a search finds no matching element, and sorting performs no
rearrangement. Pointer arguments on such a call shall still have valid values, as described
in 7.1.4.
2 The implementation shall ensure that the second argument of the comparison function
(when called from bsearch), or both arguments (when called from qsort), are
pointers to elements of the array.[263] The first argument when called from bsearch
shall equal key.
Footnote 263) That is, if the value passed is p, then the following expressions are always nonzero:
((char *)p - (char *)base) % size == 0
(char *)p >= (char *)base
(char *)p < (char *)base + nmemb * size
3 The comparison function shall not alter the contents of the array. The implementation
may reorder elements of the array between calls to the comparison function, but shall not
alter the contents of any individual element.
4 When the same objects (consisting of size bytes, irrespective of their current positions
in the array) are passed more than once to the comparison function, the results shall be
consistent with one another. That is, for qsort they shall define a total ordering on the
array, and for bsearch the same object shall always compare the same way with the
key.
5 A sequence point occurs immediately before and immediately after each call to the
comparison function, and also between any call to the comparison function and any
movement of the objects passed as arguments to that call.
<IP_ADDRESS> [The bsearch function]
1 Synopsis
#include <stdlib.h>
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Description
2 The bsearch function searches an array of nmemb objects, the initial element of which
is pointed to by base, for an element that matches the object pointed to by key. The
size of each element of the array is specified by size.
3 The comparison function pointed to by compar is called with two arguments that point
to the key object and to an array element, 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 element. The array
shall consist of: all the elements that compare less than, all the elements that compare
equal to, and all the elements that compare greater than the key object, in that order.[264]
Returns
Footnote 264) In practice, the entire array is sorted according to the comparison function.
4 The bsearch function returns a pointer to a matching element of the array, or a null
pointer if no match is found. If two elements compare as equal, which element is
matched is unspecified.
<IP_ADDRESS> [The qsort function]
1 Synopsis
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Description
2 The qsort function sorts an array of nmemb objects, the initial element of which is
pointed to by base. The size of each object is specified by size.
3 The contents of the array are sorted into 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.
4 If two elements compare as equal, their order in the resulting sorted array is unspecified.
Returns
5 The qsort function returns no value.
7.20.6 [Integer arithmetic functions]
<IP_ADDRESS> [The abs, labs and llabs functions]
1 Synopsis
#include <stdlib.h>
int abs(int j);
long int labs(long int j);
long long int llabs(long long int j);
Description
2 The abs, labs, and llabs functions compute the absolute value of an integer j. If the
result cannot be represented, the behavior is undefined.[265]
Returns
Footnote 265) The absolute value of the most negative number cannot be represented in two’s complement.
3 The abs, labs, and llabs, functions return the absolute value.
<IP_ADDRESS> [The div, ldiv, and lldiv functions]
1 Synopsis
#include <stdlib.h>
div_t div(int numer, int denom);
ldiv_t ldiv(long int numer, long int denom);
lldiv_t lldiv(long long int numer, long long int denom);
Description
2 The div, ldiv, and lldiv, functions compute numer / denom and numer %
denom in a single operation.
Returns
3 The div, ldiv, and lldiv functions return a structure of type div_t, ldiv_t, and
lldiv_t, respectively, comprising both the quotient and the remainder. The structures
shall contain (in either order) the members quot (the quotient) and rem (the remainder),
each of which has the same type as the arguments numer and denom. If either part of
the result cannot be represented, the behavior is undefined.
7.20.7 [Multibyte/wide character conversion functions]
1 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 conversion 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 conversion
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.[266] Changing the LC_CTYPE category causes the conversion state of these
functions to be indeterminate.
Footnote 266) If the locale employs special bytes to change the shift state, these bytes do not produce separate wide
character codes, but are grouped with an adjacent multibyte character.
<IP_ADDRESS> [The mblen function]
1 Synopsis
#include <stdlib.h>
int mblen(const char *s, size_t n);
Description
2 If s is not a null pointer, the mblen function determines the number of bytes contained
in the multibyte character pointed to by s. Except that the conversion state of the
mbtowc function is not affected, it is equivalent to
mbtowc((wchar_t *)0, s, n);
3 The implementation shall behave as if no library function calls the mblen function.
Returns
4 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 are contained in 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 (<IP_ADDRESS>).
<IP_ADDRESS> [The mbtowc function]
1 Synopsis
#include <stdlib.h>
int mbtowc(wchar_t * restrict pwc,
const char * restrict s,
size_t n);
Description
2 If s is not a null pointer, the mbtowc function inspects at most n bytes beginning with
the byte pointed to by s to determine the number of bytes needed to complete the next
multibyte character (including any shift sequences). If the function determines that the
next multibyte character is complete and valid, it determines the value of the
corresponding wide character and then, if pwc is not a null pointer, stores that value in
the object pointed to by pwc. If the corresponding wide character is the null wide
character, the function is left in the initial conversion state.
3 The implementation shall behave as if no library function calls the mbtowc function.
Returns
4 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 are contained in 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).
5 In no case will the value returned be greater than n or the value of the MB_CUR_MAX
macro.
<IP_ADDRESS> [The wctomb function]
1 Synopsis
#include <stdlib.h>
int wctomb(char *s, wchar_t wc);
Description
2 The wctomb function determines the number of bytes needed to represent the multibyte
character corresponding to the wide character given by wc (including any shift
sequences), and stores the multibyte character representation in the array whose first
element is pointed to by s (if s is not a null pointer). At most MB_CUR_MAX characters
are stored. If wc is a null wide character, a null byte is stored, preceded by any shift
sequence needed to restore the initial shift state, and the function is left in the initial
conversion state.
3 The implementation shall behave as if no library function calls the wctomb function.
Returns
4 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 wc does not correspond
to a valid multibyte character, or returns the number of bytes that are contained in the
multibyte character corresponding to the value of wc.
5 In no case will the value returned be greater than the value of the MB_CUR_MAX macro.
7.20.8 [Multibyte/wide string conversion functions]
1 The behavior of the multibyte string functions is affected by the LC_CTYPE category of
the current locale.
<IP_ADDRESS> [The mbstowcs function]
1 Synopsis
#include <stdlib.h>
size_t mbstowcs(wchar_t * restrict pwcs,
const char * restrict s,
size_t n);
Description
2 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 wide
characters and stores not more than n wide characters into the array pointed to by pwcs.
No multibyte characters that follow a null character (which is converted into a null wide
character) will be examined or converted. Each multibyte character is converted as if by
a call to the mbtowc function, except that the conversion state of the mbtowc function is
not affected.
3 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
4 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 null wide character, if any.[267]
Footnote 267) The array will not be null-terminated if the value returned is n.
<IP_ADDRESS> [The wcstombs function]
1 Synopsis
#include <stdlib.h>
size_t wcstombs(char * restrict s,
const wchar_t * restrict pwcs,
size_t n);
Description
2 The wcstombs function converts a sequence of wide characters from the array pointed
to by pwcs into a sequence of corresponding 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 wide character is converted as if by a call to the wctomb
function, except that the conversion state of the wctomb function is not affected.
3 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
4 If a wide character 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.[267]
Footnote 267) The array will not be null-terminated if the value returned is n.
7.21 [String handling <string.h>]
7.21.1 [String function conventions]
1 The header <string.h> 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.[268] The type is size_t and the macro is NULL (both described in
7.17). 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.
Footnote 268) See ‘‘future library directions’’ (7.26.11).
2 Where an argument declared as size_t n specifies the length of the array for a
function, n can have the value zero on a call to that function. Unless explicitly stated
otherwise in the description of a particular function in this subclause, pointer arguments
on such a call shall still have valid values, as described in 7.1.4. On such a call, a
function that locates a character finds no occurrence, a function that compares two
character sequences returns zero, and a function that copies characters copies zero
characters.
3 For all functions in this subclause, each character shall be interpreted as if it had the type
unsigned char (and therefore every possible object representation is valid and has a
different value).
7.21.2 [Copying functions]
<IP_ADDRESS> [The memcpy function]
1 Synopsis
#include <string.h>
void *memcpy(void * restrict s1,
const void * restrict s2,
size_t n);
Description
2 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
3 The memcpy function returns the value of s1.
<IP_ADDRESS> [The memmove function]
1 Synopsis
#include <string.h>
void *memmove(void *s1, const void *s2, size_t n);
Description
2 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
3 The memmove function returns the value of s1.
<IP_ADDRESS> [The strcpy function]
1 Synopsis
#include <string.h>
char *strcpy(char * restrict s1,
const char * restrict s2);
Description
2 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
3 The strcpy function returns the value of s1.
<IP_ADDRESS> [The strncpy function]
1 Synopsis
#include <string.h>
char *strncpy(char * restrict s1,
const char * restrict s2,
size_t n);
Description
2 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.[269] If copying takes place between objects that overlap, the behavior is undefined.
Footnote 269) Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will
not be null-terminated.
3 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
4 The strncpy function returns the value of s1.
7.21.3 [Concatenation functions]
<IP_ADDRESS> [The strcat function]
1 Synopsis
#include <string.h>
char *strcat(char * restrict s1,
const char * restrict s2);
Description
2 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
3 The strcat function returns the value of s1.
<IP_ADDRESS> [The strncat function]
1 Synopsis
#include <string.h>
char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);
Description
2 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.[270] If copying
takes place between objects that overlap, the behavior is undefined.
Returns
Footnote 270) Thus, the maximum number of characters that can end up in the array pointed to by s1 is
strlen(s1)+n+1.
3 The strncat function returns the value of s1.
Forward references: the strlen function (<IP_ADDRESS>).
7.21.4 [Comparison functions]
1 The sign of a nonzero value returned by the comparison functions memcmp, strcmp,
and strncmp 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.
<IP_ADDRESS> [The memcmp function]
1 Synopsis
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
Description
2 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.[271]
Returns
Footnote 271) The contents of ‘‘holes’’ used as padding for purposes of alignment within structure objects are
indeterminate. Strings shorter than their allocated space and unions may also cause problems in
comparison.
3 The memcmp function returns an integer greater than, equal to, or less than zero,
accordingly as the object pointed to by s1 is greater than, equal to, or less than the object
pointed to by s2.
<IP_ADDRESS> [The strcmp function]
1 Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);
Description
2 The strcmp function compares the string pointed to by s1 to the string pointed to by
s2.
Returns
3 The strcmp function returns an integer greater than, equal to, or less than zero,
accordingly as the string pointed to by s1 is greater than, equal to, or less than the string
pointed to by s2.
<IP_ADDRESS> [The strcoll function]
1 Synopsis
#include <string.h>
int strcoll(const char *s1, const char *s2);
Description
2 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
3 The strcoll function returns an integer greater than, equal to, or less than zero,
accordingly 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.
<IP_ADDRESS> [The strncmp function]
1 Synopsis
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);
Description
2 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
3 The strncmp function returns an integer greater than, equal to, or less than zero,
accordingly 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.
<IP_ADDRESS> [The strxfrm function]
1 Synopsis
#include <string.h>
size_t strxfrm(char * restrict s1,
const char * restrict s2,
size_t n);
Description
2 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
3 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.
4 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)
7.21.5 [Search functions]
<IP_ADDRESS> [The memchr function]
1 Synopsis
#include <string.h>
void *memchr(const void *s, int c, size_t n);
Description
2 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
3 The memchr function returns a pointer to the located character, or a null pointer if the
character does not occur in the object.
<IP_ADDRESS> [The strchr function]
1 Synopsis
#include <string.h>
char *strchr(const char *s, int c);
Description
2 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
3 The strchr function returns a pointer to the located character, or a null pointer if the
<IP_ADDRESS> [The strcspn function]
1 Synopsis
#include <string.h>
size_t strcspn(const char *s1, const char *s2);
Description
2 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
3 The strcspn function returns the length of the segment.
<IP_ADDRESS> [The strpbrk function]
1 Synopsis
#include <string.h>
char *strpbrk(const char *s1, const char *s2);
Description
2 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
3 The strpbrk function returns a pointer to the character, or a null pointer if no character
from s2 occurs in s1.
<IP_ADDRESS> [The strrchr function]
1 Synopsis
#include <string.h>
char *strrchr(const char *s, int c);
Description
2 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
3 The strrchr function returns a pointer to the character, or a null pointer if c does not
occur in the string.
<IP_ADDRESS> [The strspn function]
1 Synopsis
#include <string.h>
size_t strspn(const char *s1, const char *s2);
Description
2 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
3 The strspn function returns the length of the segment.
<IP_ADDRESS> [The strstr function]
1 Synopsis
#include <string.h>
char *strstr(const char *s1, const char *s2);
Description
2 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
3 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.
<IP_ADDRESS> [The strtok function]
1 Synopsis
#include <string.h>
char *strtok(char * restrict s1,
const char * restrict s2);
Description
2 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 a non-null first argument; subsequent calls in the
sequence have a null first argument. The separator string pointed to by s2 may be
different from call to call.
3 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.
4 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.
5 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.
6 The implementation shall behave as if no library function calls the strtok function.
Returns
7 The strtok function returns a pointer to the first character of a token, or a null pointer
if there is no token.
8 EXAMPLE
#include <string.h>
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
7.21.6 [Miscellaneous functions]
<IP_ADDRESS> [The memset function]
1 Synopsis
#include <string.h>
void *memset(void *s, int c, size_t n);
Description
2 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
3 The memset function returns the value of s.
<IP_ADDRESS> [The strerror function]
1 Synopsis
#include <string.h>
char *strerror(int errnum);
Description
2 The strerror function maps the number in errnum to a message string. Typically,
the values for errnum come from errno, but strerror shall map any value of type
int to a message.
3 The implementation shall behave as if no library function calls the strerror function.
Returns
4 The strerror function returns a pointer to the string, the contents of which are locale-
specific. The array pointed to shall not be modified by the program, but may be
overwritten by a subsequent call to the strerror function.
<IP_ADDRESS> [The strlen function]
1 Synopsis
#include <string.h>
size_t strlen(const char *s);
Description
2 The strlen function computes the length of the string pointed to by s.
Returns
3 The strlen function returns the number of characters that precede the terminating null
character.
7.22 [Type-generic math <tgmath.h>]
1 The header <tgmath.h> includes the headers <math.h> and <complex.h> and
defines several type-generic macros.
2 Of the <math.h> and <complex.h> functions without an f (float) or l (long
double) suffix, several have one or more parameters whose corresponding real type is
double. For each such function, except modf, there is a corresponding type-generic
macro.[272] The parameters whose corresponding real type is double in the function
synopsis are generic parameters. Use of the macro invokes a function whose
corresponding real type and type domain are determined by the arguments for the generic
parameters.[273]
Footnote 272) Like other function-like macros in Standard libraries, each type-generic macro can be suppressed to
make available the corresponding ordinary function.
Footnote 273) If the type of the argument is not compatible with the type of the parameter for the selected function,
the behavior is undefined.
3 Use of the macro invokes a function whose generic parameters have the corresponding
real type determined as follows:
— First, if any argument for generic parameters has type long double, the type
determined is long double.
— Otherwise, if any argument for generic parameters has type double or is of integer
type, the type determined is double.
— Otherwise, the type determined is float.
4 For each unsuffixed function in <math.h> for which there is a function in
<complex.h> with the same name except for a c prefix, the corresponding type-
generic macro (for both functions) has the same name as the function in <math.h>. The
corresponding type-generic macro for fabs and cabs is fabs.
<math.h> <complex.h> type-generic
function function macro
acos cacos acos
asin casin asin
atan catan atan
acosh cacosh acosh
asinh casinh asinh
atanh catanh atanh
cos ccos cos
sin csin sin
tan ctan tan
cosh ccosh cosh
sinh csinh sinh
tanh ctanh tanh
exp cexp exp
log clog log
pow cpow pow
sqrt csqrt sqrt
fabs cabs fabs
If at least one argument for a generic parameter is complex, then use of the macro invokes
a complex function; otherwise, use of the macro invokes a real function.
5 For each unsuffixed function in <math.h> without a c-prefixed counterpart in
<complex.h> (except modf), the corresponding type-generic macro has the same
name as the function. These type-generic macros are:
atan2 fma llround remainder
cbrt fmax log10 remquo
ceil fmin log1p rint
copysign fmod log2 round
erf frexp logb scalbn
erfc hypot lrint scalbln
exp2 ilogb lround tgamma
expm1 ldexp nearbyint trunc
fdim lgamma nextafter
floor llrint nexttoward
If all arguments for generic parameters are real, then use of the macro invokes a real
function; otherwise, use of the macro results in undefined behavior.
6 For each unsuffixed function in <complex.h> that is not a c-prefixed counterpart to a
function in <math.h>, the corresponding type-generic macro has the same name as the
function. These type-generic macros are:
carg conj creal
cimag cproj
Use of the macro with any real or complex argument invokes a complex function.
7 EXAMPLE With the declarations
#include <tgmath.h>
int n;
float f;
double d;
long double ld;
float complex fc;
double complex dc;
long double complex ldc;
functions invoked by use of type-generic macros are shown in the following table:
macro use invokes
exp(n) exp(n), the function
acosh(f) acoshf(f)
sin(d) sin(d), the function
atan(ld) atanl(ld)
log(fc) clogf(fc)
sqrt(dc) csqrt(dc)
pow(ldc, f) cpowl(ldc, f)
remainder(n, n) remainder(n, n), the function
nextafter(d, f) nextafter(d, f), the function
nexttoward(f, ld) nexttowardf(f, ld)
copysign(n, ld) copysignl(n, ld)
ceil(fc) undefined behavior
rint(dc) undefined behavior
fmax(ldc, ld) undefined behavior
carg(n) carg(n), the function
cproj(f) cprojf(f)
creal(d) creal(d), the function
cimag(ld) cimagl(ld)
fabs(fc) cabsf(fc)
carg(dc) carg(dc), the function
cproj(ldc) cprojl(ldc)
7.23 [Date and time <time.h>]
7.23.1 [Components of time]
1 The header <time.h> defines two macros, and declares several types and 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.
2 The macros defined are NULL (described in 7.17); and
CLOCKS_PER_SEC
which expands to an expression with type clock_t (described below) that is the
number per second of the value returned by the clock function.
3 The types declared are size_t (described in 7.17);
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.
4 The range and precision of times representable in clock_t and time_t are
implementation-defined. The tm 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.[274]
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.
Footnote 274) The range [0, 60] for tm_sec allows for a positive leap second.
7.23.2 [Time manipulation functions]
<IP_ADDRESS> [The clock function]
1 Synopsis
#include <time.h>
clock_t clock(void);
Description
2 The clock function determines the processor time used.
Returns
3 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 CLOCKS_PER_SEC. If
the processor time used is not available or its value cannot be represented, the function
returns the value (clock_t)(-1).[275]
Footnote 275) In order to measure the time spent in a program, the clock function should be called at the start of
the program and its return value subtracted from the value returned by subsequent calls.
<IP_ADDRESS> [The difftime function]
1 Synopsis
#include <time.h>
double difftime(time_t time1, time_t time0);
Description
2 The difftime function computes the difference between two calendar times: time1 -
time0.
Returns
3 The difftime function returns the difference expressed in seconds as a double.
<IP_ADDRESS> [The mktime function]
1 Synopsis
#include <time.h>
time_t mktime(struct tm *timeptr);
Description
2 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.[276] 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
Footnote 276) Thus, a positive or zero value for tm_isdst causes the mktime function to presume initially that
Daylight Saving Time, respectively, is or is not in effect for the specified time. A negative value
causes it to attempt to determine whether Daylight Saving Time is in effect for the specified time.
3 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).
4 EXAMPLE What day of the week is July 4, 2001?
#include <stdio.h>
#include <time.h>
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) == (time_t)(-1))
time_str.tm_wday = 7;
printf("%s\n", wday[time_str.tm_wday]);
<IP_ADDRESS> [The time function]
1 Synopsis
#include <time.h>
time_t time(time_t *timer);
Description
2 The time function determines the current calendar time. The encoding of the value is
unspecified.
Returns
3 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.
7.23.3 [Time conversion functions]
1 Except for the strftime function, these functions each return a pointer to one of two
types of static objects: a broken-down time structure or an array of char. Execution of
any of the functions that return a pointer to one of these object types may overwrite the
information in any object of the same type pointed to by the value returned from any
previous call to any of them. The implementation shall behave as if no other library
functions call these functions.
<IP_ADDRESS> [The asctime function]
1 Synopsis
#include <time.h>
char *asctime(const struct tm *timeptr);
Description
2 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
3 The asctime function returns a pointer to the string.
<IP_ADDRESS> [The ctime function]
1 Synopsis
#include <time.h>
char *ctime(const time_t *timer);
Description
2 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
3 The ctime function returns the pointer returned by the asctime function with that
broken-down time as argument.
Forward references: the localtime function (<IP_ADDRESS>).
<IP_ADDRESS> [The gmtime function]
1 Synopsis
#include <time.h>
struct tm *gmtime(const time_t *timer);
Description
2 The gmtime function converts the calendar time pointed to by timer into a broken-
down time, expressed as UTC.
Returns
3 The gmtime function returns a pointer to the broken-down time, or a null pointer if the
specified time cannot be converted to UTC.
<IP_ADDRESS> [The localtime function]
1 Synopsis
#include <time.h>
struct tm *localtime(const time_t *timer);
Description
2 The localtime function converts the calendar time pointed to by timer into a
broken-down time, expressed as local time.
Returns
3 The localtime function returns a pointer to the broken-down time, or a null pointer if
the specified time cannot be converted to local time.
<IP_ADDRESS> [The strftime function]
1 Synopsis
#include <time.h>
size_t strftime(char * restrict s,
size_t maxsize,
const char * restrict format,
const struct tm * restrict timeptr);
Description
2 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 specifiers and ordinary multibyte characters. A conversion specifier
consists of a % character, possibly followed by an E or O modifier character (described
below), followed by a character that determines the behavior of the conversion specifier.
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.
3 Each conversion specifier is replaced by appropriate characters as described in the
following list. The appropriate characters are determined using the LC_TIME category
of the current locale and by the values of zero or more members of the broken-down time
structure pointed to by timeptr, as specified in brackets in the description. If any of
the specified values is outside the normal range, the characters stored are unspecified.
%a is replaced by the locale’s abbreviated weekday name. [tm_wday]
%A is replaced by the locale’s full weekday name. [tm_wday]
%b is replaced by the locale’s abbreviated month name. [tm_mon]
%B is replaced by the locale’s full month name. [tm_mon]
%c is replaced by the locale’s appropriate date and time representation. [all specified
in 7.23.1]
%C is replaced by the year divided by 100 and truncated to an integer, as a decimal
number (00−99). [tm_year]
%d is replaced by the day of the month as a decimal number (01−31). [tm_mday]
%D is equivalent to ‘‘%m/%d/%y’’. [tm_mon, tm_mday, tm_year]
%e is replaced by the day of the month as a decimal number (1−31); a single digit is
preceded by a space. [tm_mday]
%F is equivalent to ‘‘%Y−%m−%d’’ (the ISO 8601 date format). [tm_year, tm_mon,
tm_mday]
%g is replaced by the last 2 digits of the week-based year (see below) as a decimal
number (00−99). [tm_year, tm_wday, tm_yday]
%G is replaced by the week-based year (see below) as a decimal number (e.g., 1997).
[tm_year, tm_wday, tm_yday]
%h is equivalent to ‘‘%b’’. [tm_mon]
%H is replaced by the hour (24-hour clock) as a decimal number (00−23). [tm_hour]
%I is replaced by the hour (12-hour clock) as a decimal number (01−12). [tm_hour]
%j is replaced by the day of the year as a decimal number (001−366). [tm_yday]
%m is replaced by the month as a decimal number (01−12). [tm_mon]
%M is replaced by the minute as a decimal number (00−59). [tm_min]
%n is replaced by a new-line character.
%p is replaced by the locale’s equivalent of the AM/PM designations associated with a
12-hour clock. [tm_hour]
%r is replaced by the locale’s 12-hour clock time. [tm_hour, tm_min, tm_sec]
%R is equivalent to ‘‘%H:%M’’. [tm_hour, tm_min]
%S is replaced by the second as a decimal number (00−60). [tm_sec]
%t is replaced by a horizontal-tab character.
%T is equivalent to ‘‘%H:%M:%S’’ (the ISO 8601 time format). [tm_hour, tm_min,
tm_sec]
%u is replaced by the ISO 8601 weekday as a decimal number (1−7), where Monday
is 1. [tm_wday]
%U is replaced by the week number of the year (the first Sunday as the first day of week
1) as a decimal number (00−53). [tm_year, tm_wday, tm_yday]
%V is replaced by the ISO 8601 week number (see below) as a decimal number
(01−53). [tm_year, tm_wday, tm_yday]
%w is replaced by the weekday as a decimal number (0−6), where Sunday is 0.
[tm_wday]
%W is replaced by the week number of the year (the first Monday as the first day of
week 1) as a decimal number (00−53). [tm_year, tm_wday, tm_yday]
%x is replaced by the locale’s appropriate date representation. [all specified in 7.23.1]
%X is replaced by the locale’s appropriate time representation. [all specified in 7.23.1]
%y is replaced by the last 2 digits of the year as a decimal number (00−99).
[tm_year]
%Y is replaced by the year as a decimal number (e.g., 1997). [tm_year]
%z is replaced by the offset from UTC in the ISO 8601 format ‘‘−0430’’ (meaning 4
hours 30 minutes behind UTC, west of Greenwich), or by no characters if no time
zone is determinable. [tm_isdst]
%Z is replaced by the locale’s time zone name or abbreviation, or by no characters if no
time zone is determinable. [tm_isdst]
%% is replaced by %.
4 Some conversion specifiers can be modified by the inclusion of an E or O modifier
character to indicate an alternative format or specification. If the alternative format or
specification does not exist for the current locale, the modifier is ignored.
%Ec is replaced by the locale’s alternative date and time representation.
%EC is replaced by the name of the base year (period) in the locale’s alternative
representation.
%Ex is replaced by the locale’s alternative date representation.
%EX is replaced by the locale’s alternative time representation.
%Ey is replaced by the offset from %EC (year only) in the locale’s alternative
representation.
%EY is replaced by the locale’s full alternative year representation.
%Od is replaced by the day of the month, using the locale’s alternative numeric symbols
(filled as needed with leading zeros, or with leading spaces if there is no alternative
symbol for zero).
%Oe is replaced by the day of the month, using the locale’s alternative numeric symbols
(filled as needed with leading spaces).
%OH is replaced by the hour (24-hour clock), using the locale’s alternative numeric
symbols.
%OI is replaced by the hour (12-hour clock), using the locale’s alternative numeric
symbols.
%Om is replaced by the month, using the locale’s alternative numeric symbols.
%OM is replaced by the minutes, using the locale’s alternative numeric symbols.
%OS is replaced by the seconds, using the locale’s alternative numeric symbols.
%Ou is replaced by the ISO 8601 weekday as a number in the locale’s alternative
representation, where Monday is 1.
%OU is replaced by the week number, using the locale’s alternative numeric symbols.
%OV is replaced by the ISO 8601 week number, using the locale’s alternative numeric
symbols.
%Ow is replaced by the weekday as a number, using the locale’s alternative numeric
symbols.
%OW is replaced by the week number of the year, using the locale’s alternative numeric
symbols.
%Oy is replaced by the last 2 digits of the year, using the locale’s alternative numeric
symbols.
5 %g, %G, and %V give values according to the ISO 8601 week-based year. In this system,
weeks begin on a Monday and week 1 of the year is the week that includes January 4th,
which is also the week that includes the first Thursday of the year, and is also the first
week that contains at least four days in the year. If the first Monday of January is the
2nd, 3rd, or 4th, the preceding days are part of the last week of the preceding year; thus,
for Saturday 2nd January 1999, %G is replaced by 1998 and %V is replaced by 53. If
December 29th, 30th, or 31st is a Monday, it and any following days are part of week 1 of
the following year. Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and
%V is replaced by 01.
6 If a conversion specifier is not one of the above, the behavior is undefined.
7 In the "C" locale, the E and O modifiers are ignored and the replacement strings for the
following specifiers are:
%a the first three characters of %A.
%A one of ‘‘Sunday’’, ‘‘Monday’’, ... , ‘‘Saturday’’.
%b the first three characters of %B.
%B one of ‘‘January’’, ‘‘February’’, ... , ‘‘December’’.
%c equivalent to ‘‘%a %b %e %T %Y’’.
%p one of ‘‘AM’’ or ‘‘PM’’.
%r equivalent to ‘‘%I:%M:%S %p’’.
%x equivalent to ‘‘%m/%d/%y’’.
%X equivalent to %T.
%Z implementation-defined.
Returns
8 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.
7.24 [Extended multibyte and wide character utilities <wchar.h>]
7.24.1 [Introduction]
1 The header <wchar.h> declares four data types, one tag, four macros, and many
functions.[277]
Footnote 277) See ‘‘future library directions’’ (7.26.12).
2 The types declared are wchar_t and size_t (both described in 7.17);
mbstate_t
which is an object type other than an array type that can hold the conversion state
information necessary to convert between sequences of multibyte characters and wide
characters;
wint_t
which is an integer type unchanged by default argument promotions that can hold any
value corresponding to members of the extended character set, as well as at least one
value that does not correspond to any member of the extended character set (see WEOF
below);[278] and
struct tm
which is declared as an incomplete structure type (the contents are described in 7.23.1).
Footnote 278) wchar_t and wint_t can be the same integer type.
3 The macros defined are NULL (described in 7.17); WCHAR_MIN and WCHAR_MAX
(described in 7.18.3); and
WEOF
which expands to a constant expression of type wint_t whose value does not
correspond to any member of the extended character set.[279] It is accepted (and returned)
by several functions in this subclause to indicate end-of-file, that is, no more input from a
stream. It is also used as a wide character value that does not correspond to any member
of the extended character set.
Footnote 279) The value of the macro WEOF may differ from that of EOF and need not be negative.
4 The functions declared are grouped as follows:
— Functions that perform input and output of wide characters, or multibyte characters,
or both;
— Functions that provide wide string numeric conversion;
— Functions that perform general wide string manipulation;
— Functions for wide string date and time conversion; and
— Functions that provide extended capabilities for conversion between multibyte and
wide character sequences.
5 Unless explicitly stated otherwise, if the execution of a function described in this
subclause causes copying to take place between objects that overlap, the behavior is
undefined.
7.24.2 [Formatted wide character input/output functions]
1 The formatted wide character input/output functions shall behave as if there is a sequence
point after the actions associated with each specifier.[280]
Footnote 280) The fwprintf functions perform writes to memory for the %n specifier.
<IP_ADDRESS> [The fwprintf function]
1 Synopsis
#include <stdio.h>
#include <wchar.h>
int fwprintf(FILE * restrict stream,
const wchar_t * restrict format, ...);
Description
2 The fwprintf function writes output to the stream pointed to by stream, under
control of the wide 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 fwprintf function returns
when the end of the format string is encountered.
3 The format is composed of zero or more directives: ordinary wide characters (not %),
which are copied unchanged to the output stream; and conversion specifications, each of
which results in fetching zero or more subsequent arguments, converting them, if
applicable, according to the corresponding conversion specifier, and then writing the
result to the output stream.
4 Each conversion specification is introduced by the wide character %. After the %, the
following appear in sequence:
— Zero or more flags (in any order) that modify the meaning of the conversion
specification.
— An optional minimum field width. If the converted value has fewer wide characters
than the field width, it is padded with spaces (by default) on the left (or right, if the
left adjustment flag, described later, has been given) to the field width. The field
width takes the form of an asterisk * (described later) or a nonnegative decimal
integer.[281]
— 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
wide character for a, A, e, E, f, and F conversions, the maximum number of
significant digits for the g and G conversions, or the maximum number of wide
characters to be written for s conversions. The precision takes the form of a period
(.) followed either by an asterisk * (described later) or by an optional decimal
integer; if only the period is specified, the precision is taken as zero. If a precision
appears with any other conversion specifier, the behavior is undefined.
— An optional length modifier that specifies the size of the argument.
— A conversion specifier wide character that specifies the type of conversion to be
applied.
Footnote 281) Note that 0 is taken as a flag, not as the beginning of a field width.
5 As noted above, a field width, or precision, or both, may be indicated by an asterisk. 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 the
precision were omitted.
6 The flag wide characters and their meanings are:
- The result of the conversion is left-justified within the field. (It is right-justified if
this flag is not specified.)
+ The result of a signed conversion always begins with a plus or minus sign. (It
begins with a sign only when a negative value is converted if this flag is not
specified.)[282]
space If the first wide character of a signed conversion is not a sign, or if a signed
conversion results in no wide characters, a space is prefixed to the result. If the
space and + flags both appear, the space flag is ignored.
# The result is converted to an ‘‘alternative form’’. For o conversion, it increases
the precision, if and only if necessary, to force the first digit of the result to be a
zero (if the value and precision are both 0, a single 0 is printed). For x (or X)
conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g,
and G conversions, the result of converting a floating-point number always
contains a decimal-point wide character, even if no digits follow it. (Normally, a
decimal-point wide character appears in the result of these conversions only if a
digit follows it.) For g and G conversions, trailing zeros are not removed from the
result. For other conversions, the behavior is undefined.
0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros
(following any indication of sign or base) are used to pad to the field width rather
than performing space padding, except when converting an infinity or NaN. If the
0 and - flags both appear, the 0 flag is ignored. For d, i, o, u, x, and X
conversions, if a precision is specified, the 0 flag is ignored. For other
conversions, the behavior is undefined.
Footnote 282) The results of all floating conversions of a negative zero, and of negative values that round to zero,
include a minus sign.
7 The length modifiers and their meanings are:
hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
signed char or unsigned char argument (the argument will have
been promoted according to the integer promotions, but its value shall be
converted to signed char or unsigned char before printing); or that
a following n conversion specifier applies to a pointer to a signed char
argument.
h Specifies 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 integer promotions, but its value shall
be converted to short int or unsigned short int before printing);
or that a following n conversion specifier applies to a pointer to a short
int argument.
l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
long int or unsigned long int argument; that a following n
conversion specifier applies to a pointer to a long int argument; that a
following c conversion specifier applies to a wint_t argument; that a
following s conversion specifier applies to a pointer to a wchar_t
argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion
specifier.
ll (ell-ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
long long int or unsigned long long int argument; or that a
following n conversion specifier applies to a pointer to a long long int
argument.
j Specifies that a following d, i, o, u, x, or X conversion specifier applies to
an intmax_t or uintmax_t argument; or that a following n conversion
specifier applies to a pointer to an intmax_t argument.
z Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
size_t or the corresponding signed integer type argument; or that a
following n conversion specifier applies to a pointer to a signed integer type
corresponding to size_t argument.
t Specifies that a following d, i, o, u, x, or X conversion specifier applies to a
ptrdiff_t or the corresponding unsigned integer type argument; or that a
following n conversion specifier applies to a pointer to a ptrdiff_t
argument.
L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier
applies to a long double argument.
If a length modifier appears with any conversion specifier other than as specified above,
the behavior is undefined.
8 The conversion specifiers and their meanings are:
d,i The int argument is converted to signed decimal in the style [−]dddd. The
precision specifies the minimum number of digits to appear; if the value
being converted can be represented in fewer digits, it is expanded with
leading zeros. The default precision is 1. The result of converting a zero
value with a precision of zero is no wide characters.
o,u,x,X The unsigned int argument is converted to unsigned octal (o), unsigned
decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; 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 is expanded
with leading zeros. The default precision is 1. The result of converting a
zero value with a precision of zero is no wide characters.
f,F A double argument representing a floating-point number is converted to
decimal notation in the style [−]ddd.ddd, where the number of digits after
the decimal-point wide character is equal to the precision specification. If the
precision is missing, it is taken as 6; if the precision is zero and the # flag is
not specified, no decimal-point wide character appears. If a decimal-point
wide character appears, at least one digit appears before it. The value is
rounded to the appropriate number of digits.
A double argument representing an infinity is converted in one of the styles
[-]inf or [-]infinity — which style is implementation-defined. A
double argument representing a NaN is converted in one of the styles
[-]nan or [-]nan(n-wchar-sequence) — which style, and the meaning of
any n-wchar-sequence, is implementation-defined. The F conversion
specifier produces INF, INFINITY, or NAN instead of inf, infinity, or
nan, respectively.[283]
e,E A double argument representing a floating-point number is converted in the
style [−]d.ddd e±dd, where there is one digit (which is nonzero if the
argument is nonzero) before the decimal-point wide character 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 and the # flag is not specified, no decimal-point
wide character appears. The value is rounded to the appropriate number of
digits. The E conversion specifier produces a number with E instead of e
introducing the exponent. The exponent always contains at least two digits,
and only as many more digits as necessary to represent the exponent. If the
value is zero, the exponent is zero.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
g,G A double argument representing a floating-point number is converted in
style f or e (or in style F or E in the case of a G conversion specifier),
depending on the value converted and the precision. Let P equal the
precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero.
Then, if a conversion with style E would have an exponent of X :
— if P > X ≥ −4, the conversion is with style f (or F) and precision
P − (X + 1).
— otherwise, the conversion is with style e (or E) and precision P − 1.
Finally, unless the # flag is used, any trailing zeros are removed from the
fractional portion of the result and the decimal-point wide character is
removed if there is no fractional portion remaining.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
a,A A double argument representing a floating-point number is converted in the
style [−]0xh.hhhh p±d, where there is one hexadecimal digit (which is
nonzero if the argument is a normalized floating-point number and is
otherwise unspecified) before the decimal-point wide character[284] and the
number of hexadecimal digits after it is equal to the precision; if the precision
is missing and FLT_RADIX is a power of 2, then the precision is sufficient
for an exact representation of the value; if the precision is missing and
FLT_RADIX is not a power of 2, then the precision is sufficient to
distinguish[285] values of type double, except that trailing zeros may be
omitted; if the precision is zero and the # flag is not specified, no decimal-
point wide character appears. The letters abcdef are used for a conversion
and the letters ABCDEF for A conversion. The A conversion specifier
produces a number with X and P instead of x and p. The exponent always
contains at least one digit, and only as many more digits as necessary to
represent the decimal exponent of 2. If the value is zero, the exponent is
zero.
A double argument representing an infinity or NaN is converted in the style
of an f or F conversion specifier.
c If no l length modifier is present, the int argument is converted to a wide
character as if by calling btowc and the resulting wide character is written.
If an l length modifier is present, the wint_t argument is converted to
wchar_t and written.
s If no l length modifier is present, the argument shall be a pointer to the initial
element of a character array containing a multibyte character sequence
beginning in the initial shift state. Characters from the array are converted as
if by repeated calls to the mbrtowc function, with the conversion state
described by an mbstate_t object initialized to zero before the first
multibyte character is converted, and written up to (but not including) the
terminating null wide character. If the precision is specified, no more than
that many wide characters are written. If the precision is not specified or is
greater than the size of the converted array, the converted array shall contain a
null wide character.
If an l length modifier is present, the argument shall be a pointer to the initial
element of an array of wchar_t type. Wide characters from the array are
written up to (but not including) a terminating null wide character. If the
precision is specified, no more than that many wide characters are written. If
the precision is not specified or is greater than the size of the array, the array
shall contain a null wide character.
p The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing wide characters, in an implementation-
defined manner.
n The argument shall be a pointer to signed integer into which is written the
number of wide characters written to the output stream so far by this call to
fwprintf. No argument is converted, but one is consumed. If the
conversion specification includes any flags, a field width, or a precision, the
behavior is undefined.
% A % wide character is written. No argument is converted. The complete
conversion specification shall be %%.