Learn to develop and use open-source software, including WordPress...

Welcome to a new generation of Drupal. It’s a digital experience...

Appendix B - Standard Library

Appendix B - Standard Library

This appendix is a summary of the library defined by the ANSI standard. The standard library is not part of the C language proper, but an environment that supports standard C will provide the function declarations and type and macro definitions of this library. We have omitted a few functions that are of limited utility or easily synthesized from others; we have omitted multi-byte characters; and we have omitted discussion of locale issues; that is, properties that depend on local language, nationality, or culture.

The functions, types and macros of the standard library are declared in standard headers:

   <assert.h>  <float.h>   <math.h>    <stdarg.h>  <stdlib.h>

   <ctype.h>   <limits.h>  <setjmp.h>  <stddef.h>  <string.h>

   <errno.h>   <locale.h>  <signal.h>  <stdio.h>   <time.h>

A header can be accessed by

  #include<header>

Headers may be included in any order and any number of times. A header must be included outside of any external declaration or definition and before any use of anything it declares. A header need not be a source file.

External identifiers that begin with an underscore are reserved for use by the library, as are all other identifiers that begin with an underscore and an upper-case letter or another underscore.

B.1 Input and Output: <stdio.h>

The input and output functions, types, and macros defined in <stdio.h>represent nearly one third of the library.

A stream is a source or destination of data that may be associated with a disk or other peripheral. The library supports text streams and binary streams, although on some systems, notably UNIX, these are identical. A text stream is a sequence of lines; each line has zero or more characters and is terminated by '\n'. An environment may need to convert a text stream to or from some other representation (such as mapping '\n'to carriage return and linefeed). A binary stream is a sequence of unprocessed bytes that record internal data, with the property that if it is written, then read back on the same system, it will compare equal.

A stream is connected to a file or device by opening it; the connection is broken by closing the stream. Opening a file returns a pointer to an object of type FILE, which records whatever information is necessary to control the stream. We will use ``file pointer'' and ``stream'' interchangeably when there is no ambiguity.

When a program begins execution, the three streams stdin, stdout, and stderrare already open.

B.1.1 File Operations

The following functions deal with operations on files. The type size_tis the unsigned integral type produced by the sizeofoperator.

FILE *fopen(const char *filename, const char *mode)

fopenopens the named file, and returns a stream, or NULLif the attempt fails. Legal values for modeinclude:

"r" open text file for reading

"w" create text file for writing; discard previous contents if any

"a" append; open or create text file for writing at end of file

"r+" open text file for update (i.e., reading and writing)

"w+" create text file for update, discard previous contents if any

"a+" append; open or create text file for update, writing at end

Update mode permits reading and writing the same file; fflushor a file-positioning function must be called between a read and a write or vice versa. If the mode includes bafter the initial letter, as in "rb"or "w+b", that indicates a binary file. Filenames are limited to FILENAME_MAXcharacters. At most FOPEN_MAXfiles may be open at once.

FILE *freopen(const char *filename, const char *mode, FILE *stream)

freopenopens the file with the specified mode and associates the stream with it. It returns stream, or NULLif an error occurs. freopenis normally used to change the files associated with stdin, stdout, or stderr.

int fflush(FILE *stream)

On an output stream, fflushcauses any buffered but unwritten data to be written; on an input

stream, the effect is undefined. It returns EOFfor a write error, and zero otherwise. fflush(NULL)flushes all output streams.

int fclose(FILE *stream)

fcloseflushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOFif any errors occurred, and zero otherwise.

int remove(const char *filename)

removeremoves the named file, so that a subsequent attempt to open it will fail. It returns nonzero if the attempt fails.

int rename(const char *oldname, const char *newname)

renamechanges the name of a file; it returns non-zero if the attempt fails.

FILE *tmpfile(void)

tmpfilecreates a temporary file of mode "wb+"that will be automatically removed when closed or when the program terminates normally. tmpfilereturns a stream, or NULLif it could not create the file.

char *tmpnam(char s[L_tmpnam])

tmpnam(NULL)creates a string that is not the name of an existing file, and returns a pointer to an internal static array. tmpnam(s)stores the string in sas well as returning it as the function value; smust have room for at least L_tmpnamcharacters. tmpnamgenerates a different name each time it is called; at most TMP_MAXdifferent names are guaranteed during execution of the program. Note that tmpnamcreates a name, not a file.

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

setvbufcontrols buffering for the stream; it must be called before reading, writing or any other operation. A modeof _IOFBFcauses full buffering, _IOLBFline buffering of text files, and _IONBFno buffering. If bufis not NULL, it will be used as the buffer, otherwise a buffer will be allocated. sizedetermines the buffer size. setvbufreturns non-zero for any error.

void setbuf(FILE *stream, char *buf)

If bufis NULL, buffering is turned off for the stream. Otherwise, setbufis equivalent to

(void) setvbuf(stream, buf, _IOFBF, BUFSIZ).

B.1.2 Formatted Output

The printffunctions provide formatted output conversion.

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

fprintfconverts and writes output to streamunder the control of format. The return value is the number of characters written, or negative if an error occurred.

The format string contains two types of objects: ordinary characters, which are copied to the output stream, and conversion specifications, each of which causes conversion and printing of the next successive argument to fprintf. Each conversion specification begins with the character %and ends with a conversion character. Between the %and the conversion character there may be, in order:

  • Flags (in any order), which modify the specification:

❍     -, which specifies left adjustment of the converted argument in its field.

❍     +, which specifies that the number will always be printed with a sign.

❍     space: if the first character is not a sign, a space will be prefixed.

❍     0: for numeric conversions, specifies padding to the field width with leading zeros.

❍     #, which specifies an alternate output form. For o, the first digit will become zero. For xor X, 0xor 0Xwill be prefixed to a non-zero result. For e, E, f, g, and G, the output will always have a decimal point; for gand G, trailing zeros will not be removed.

  • A number specifying a minimum field width. The converted argument will be printed in a field at least this wide, and wider if necessary. If the converted argument has fewer characters than the field width it will be padded on the left (or right, if left adjustment has been requested) to make up the field width. The padding character is normally space, but is 0if the zero padding flag is present.
  • A period, which separates the field width from the precision.
  • A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits to be printed after the decimal point for e, E, or fconversions, or the number of significant digits for gor Gconversion, or the number of digits to be printed for an integer (leading 0s will be added to make up the necessary width).
  • A length modifier h, l(letter ell), or L. ``h'' indicates that the corresponding argument is to be printed as a shortor unsigned short; ``l'' indicates that the argument is a longor unsigned long, ``L'' indicates that the argument is a long double.

Width or precision or both may be specified as *, in which case the value is computed by converting the next argument(s), which must be int.

The conversion characters and their meanings are shown in Table B.1. If the character after the %is not a conversion character, the behavior is undefined.

Table B.1Printf Conversions

d,i      int; signed decimal notation.

o        int; unsigned octal notation (without a leading zero).

unsigned int; unsigned hexadecimal notation (without a leading 0xor 0X), using

x,X

abcdeffor 0xor ABCDEFfor 0X.

u        int; unsigned decimal notation.

c        int; single character, after conversion to unsigned char

char *; characters from the string are printed until a '\0'is reached or until the number

s of characters indicated by the precision have been printed.

double; decimal notation of the form [-]mmm.ddd, where the number of d's is given by

f the precision. The default precision is 6; a precision of 0 suppresses the decimal point.

double; decimal notation of the form [-]m.dddddde+/-xxor [-]m.ddddddE+/-xx,

e,E     where the number of d's is specified by the precision. The default precision is 6; a precision of 0 suppresses the decimal point.

double; %eor %Eis used if the exponent is less than -4 or greater than or equal to the

g,G

precision; otherwise %fis used. Trailing zeros and a trailing decimal point are not printed.

p        void *; print as a pointer (implementation-dependent representation).

int *; the number of characters written so far by this call to printfis written into the

n

argument. No argument is converted.

%        no argument is converted; print a %

int printf(const char *format, ...)printf(...)is equivalent to fprintf(stdout, ...).

int sprintf(char *s, const char *format, ...)

sprintfis the same as printfexcept that the output is written into the string s, terminated with '\0'. smust be big enough to hold the result. The return count does not include the '\0'.

int vprintf(const char *format, va_list arg)

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

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

The functions vprintf, vfprintf, and vsprintfare equivalent to the corresponding printffunctions, except that the variable argument list is replaced by arg, which has been initialized by the va_startmacro and perhaps va_argcalls. See the discussion of <stdarg.h>in Section B.7.

B.1.3 Formatted Input

The scanffunction deals with formatted input conversion.

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

fscanfreads from streamunder control of format, and assigns converted values through subsequent arguments, each of which must be a pointer. It returns when formatis exhausted. fscanfreturns EOFif end of file or an error occurs before any conversion; otherwise it returns the number of input items converted and assigned.

The format string usually contains conversion specifications, which are used to direct interpretation of input. The format string may contain:

  • Blanks or tabs, which are not ignored.
  • Ordinary characters (not %), which are expected to match the next non-white space character of the input stream.
  • Conversion specifications, consisting of a %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional h, l, or Lindicating the width of the target, and a conversion character.

A conversion specification determines the conversion of the next input field. Normally the result is placed in the variable pointed to by the corresponding argument. If assignment suppression is indicated by *, as in %*s, however, the input field is simply skipped; no assignment is made. An input field is defined as a string of non-white space characters; it extends either to the next white space character or until the field width, if specified, is exhausted. This implies that scanfwill read across line boundaries to find its input, since newlines are white space. (White space characters are blank, tab, newline, carriage return, vertical tab, and formfeed.)

The conversion character indicates the interpretation of the input field. The corresponding argument must be a pointer. The legal conversion characters are shown in Table B.2.

The conversion characters d, i, n, o, u, and xmay be preceded by hif the argument is a pointer to shortrather than int, or by l(letter ell) if the argument is a pointer to long. The conversion characters e, f, and gmay be preceded by lif a pointer to doublerather than floatis in the argument list, and by Lif a pointer to a long double.

o octal integer (with or without leading zero); int *. u unsigned decimal integer; unsigned int *. x hexadecimal integer (with or without leading 0xor 0X); int*.

characters; char*. The next input characters are placed in the indicated array, up to the number given by the width field; the default is 1. No '\0'is added. The normal skip over

c

white space characters is suppressed in this case; to read the next non-white space character, use %1s.

string of non-white space characters (not quoted); char *, pointing to an array of

s characters large enough to hold the string and a terminating '\0'that will be added.

floating-point number; float *. The input format for float's is an optional sign, a

e,f,g   string of numbers possibly containing a decimal point, and an optional exponent field containing an Eor efollowed by a possibly signed integer.

p        pointer value as printed by printf("%p");, void *.

writes into the argument the number of characters read so far by this call; int *. No input

n is read. The converted item count is not incremented.

matches the longest non-empty string of input characters from the set between brackets;

[...] char *. A '\0'is added. []...]includes ]in the set.

matches the longest non-empty string of input characters not from the set between brackets;

[^...]

char *. A '\0'is added. [^]...]includes ]in the set.

%        literal %; no assignment is made.

int scanf(const char *format, ...)scanf(...)is identical to fscanf(stdin, ...).

int sscanf(const char *s, const char *format, ...)

sscanf(s, ...)is equivalent to scanf(...)except that the input characters are taken from the string s.

B.1.4 Character Input and Output Functions

int fgetc(FILE *stream)

fgetcreturns the next character of streamas an unsigned char(converted to an int), or EOFif end of file or error occurs.

char *fgets(char *s, int n, FILE *stream)

fgetsreads at most the next n-1characters into the array s, stopping if a newline is

encountered; the newline is included in the array, which is terminated by '\0'. fgetsreturns s, or NULLif end of file or error occurs.

int fputc(int c, FILE *stream)

fputcwrites the character c(converted to an unsigend char) on stream. It returns the character written, or EOFfor error.

int fputs(const char *s, FILE *stream)

fputswrites the string s(which need not contain \n) on stream; it returns non-negative, or EOFfor an error.

int getc(FILE *stream)

getcis equivalent to fgetcexcept that if it is a macro, it may evaluate streammore than once.

int getchar(void)getcharis equivalent to getc(stdin).

char *gets(char *s)

getsreads the next input line into the array s; it replaces the terminating newline with '\0'. It returns s, or NULLif end of file or error occurs.

int putc(int c, FILE *stream)

putcis equivalent to fputcexcept that if it is a macro, it may evaluate streammore than once.

int putchar(int c)putchar(c)is equivalent to putc(c,stdout).

int puts(const char *s)

putswrites the string sand a newline to stdout. It returns EOFif an error occurs, nonnegative otherwise.

int ungetc(int c, FILE *stream)

ungetcpushes c(converted to an unsigned char) back onto stream, where it will be returned on the next read. Only one character of pushback per stream is guaranteed. EOFmay not be pushed back. ungetcreturns the character pushed back, or EOFfor error.

B.1.5 Direct Input and Output Functions

size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream)

freadreads from streaminto the array ptrat most nobjobjects of size size. freadreturns the number of objects read; this may be less than the number requested. feofand ferrormust be used to determine status.

size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)

fwritewrites, from the array ptr, nobjobjects of size sizeon stream. It returns the number of objects written, which is less than nobjon error.

B.1.6 File Positioning Functions

int fseek(FILE *stream, long offset, int origin)

fseeksets the file position for stream; a subsequent read or write will access data beginning at the new position. For a binary file, the position is set to offsetcharacters from origin, which may be SEEK_SET(beginning), SEEK_CUR(current position), or SEEK_END(end of file). For a text stream, offsetmust be zero, or a value returned by ftell(in which case originmust be SEEK_SET). fseekreturns non-zero on error.

long ftell(FILE *stream)

ftellreturns the current file position for stream, or -1on error.

void rewind(FILE *stream)rewind(fp)is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp).

int fgetpos(FILE *stream, fpos_t *ptr)fgetposrecords the current position in streamin *ptr, for subsequent use by fsetpos. The type fpos_tis suitable for recording such values. fgetposreturns non-zero on error.

int fsetpos(FILE *stream, const fpos_t *ptr)

fsetpospositions streamat the position recorded by fgetposin *ptr. fsetposreturns non-zero on error.

B.1.7 Error Functions

Many of the functions in the library set status indicators when error or end of file occur. These indicators may be set and tested explicitly. In addition, the integer expression errno(declared in <errno.h>) may contain an error number that gives further information about the most recent error.

void clearerr(FILE *stream)

clearerrclears the end of file and error indicators for stream.

int feof(FILE *stream)

feofreturns non-zero if the end of file indicator for streamis set.

int ferror(FILE *stream)

ferrorreturns non-zero if the error indicator for streamis set.

void perror(const char *s)

perror(s)prints sand an implementation-defined error message corresponding to the integer in errno, as if by

    fprintf(stderr, "%s: %s\n", s, "error message");See strerrorin Section B.3.

B.2 Character Class Tests: <ctype.h>

The header <ctype.h>declares functions for testing characters. For each function, the argument list is an int, whose value must be EOFor representable as an unsigned char, and the return value is an int. The functions return non-zero (true) if the argument csatisfies the condition described, and zero if not.

isalnum(c)

isalpha(c)or isdigit(c)is true

isalpha(c)

isupper(c)or islower(c)is true

iscntrl(c)

control character

isdigit(c)

decimal digit

isgraph(c)

printing character except space

islower(c)

lower-case letter

isprint(c)

printing character including space

ispunct(c)

printing character except space or letter or digit

isspace(c)

space, formfeed, newline, carriage return, tab, vertical tab

isupper(c)

upper-case letter

isxdigit(c) hexadecimal digit

In the seven-bit ASCII character set, the printing characters are 0x20 (' ')to 0x7E ('-'); the control characters are 0 NULto 0x1F(US), and 0x7F(DEL).

In addition, there are two functions that convert the case of letters:

int tolower(c) convert cto lower case int toupper(c) convert cto upper case

If cis an upper-case letter, tolower(c)returns the corresponding lower-case letter, toupper(c)returns the corresponding upper-case letter; otherwise it returns c.

B.3 String Functions: <string.h>

There are two groups of string functions defined in the header <string.h>. The first have names beginning with str; the second have names beginning with mem. Except for memmove, the behavior is undefined if copying takes place between overlapping objects. Comparison functions treat arguments as unsigned chararrays.

In the following table, variables sand tare of type char *; csand ctare of type const char *; nis of type size_t; and cis an intconverted to char.

char *strcpy(s,ct)    copy string ctto string s, including '\0'; return s.

copy at most ncharacters of string ctto s; return s. Pad with '\0''s

char *strncpy(s,ct,n)

if cthas fewer than ncharacters.

char *strcat(s,ct)    concatenate string ctto end of string s; return s. concatenate at most ncharacters of string ctto string s, terminate s

char *strncat(s,ct,n)

with '\0'; return s.

int strcmp(cs,ct)

compare string csto string ct, return <0 if cs<ct, 0 if cs==ct, or >0 if cs>ct.

int strncmp(cs,ct,n)

compare at most ncharacters of string csto string ct; return <0 if cs<ct, 0 if cs==ct, or >0 if cs>ct.

char *strchr(cs,c)

return pointer to first occurrence of cin csor NULLif not present.

char *strrchr(cs,c)

return pointer to last occurrence of cin csor NULLif not present.

size_t strspn(cs,ct)

return length of prefix of csconsisting of characters in ct.

size_t strcspn(cs,ct) return length of prefix of csconsisting of characters not in ct.

return pointer to first occurrence in string csof any character string ct,

char *strpbrk(cs,ct)

or NULLif not present.

char *strstr(cs,ct)

return pointer to first occurrence of string ctin cs, or NULLif not present.

size_t strlen(cs)

return length of cs.

char *strerror(n)

return pointer to implementation-defined string corresponding to error n.

char *strtok(s,ct)

strtoksearches sfor tokens delimited by characters from ct; see below.

A sequence of calls of strtok(s,ct)splits sinto tokens, each delimited by a character from ct. The first call in a sequence has a non-NULL s, it finds the first token in sconsisting of characters not in ct; it terminates that by overwriting the next character of swith '\0'and returns a pointer to the token. Each subsequent call, indicated by a NULLvalue of s, returns the next such token, searching from just past the end of the previous one. strtokreturns NULLwhen no further token is found. The string ctmay be different on each call.

The mem...functions are meant for manipulating objects as character arrays; the intent is an interface to efficient routines. In the following table, sand tare of type void *; csand ctare of type const void *; nis of type size_t; and cis an intconverted to an unsigned char.

void *memcpy(s,ct,n) copy ncharacters from ctto s, and return s. void *memmove(s,ct,n) same as memcpyexcept that it works even if the objects overlap.

int memcmp(cs,ct,n) compare the first ncharacters of cswith ct; return as with strcmp.

return pointer to first occurrence of character cin cs, or NULLif not

void *memchr(cs,c,n)

present among the first ncharacters.

void *memset(s,c,n) place character cinto first ncharacters of s, return s.

B.4 Mathematical Functions: <math.h>

The header <math.h>declares mathematical functions and macros.

The macros EDOMand ERANGE(found in <errno.h>) are non-zero integral constants that are used to signal domain and range errors for the functions; HUGE_VALis a positive doublevalue. A domain error occurs if an argument is outside the domain over which the function is defined. On a domain error, errnois set to EDOM; the return value is implementation-defined. A range error occurs if the result of the function cannot be represented as a double. If the result overflows, the function returns HUGE_VALwith the right sign, and errnois set to ERANGE. If the result underflows, the function returns zero; whether errnois set to ERANGEis implementation-defined.

In the following table, xand yare of type double, nis an int, and all functions return double.

Angles for trigonometric functions are expressed in radians.

sin(x)

sine of x

cos(x)

cosine of x

tan(x)

tangent of x

asin(x)

sin-1(x) in range [-pi/2,pi/2], x in [-1,1].

acos(x)

cos-1(x) in range [0,pi], x in [-1,1].

atan(x)

tan-1(x) in range [-pi/2,pi/2].

atan2(y,x)

tan-1(y/x) in range [-pi,pi].

sinh(x)   hyperbolic sine of x cosh(x)hyperbolic cosine of x tanh(x)hyperbolic tangent of x exp(x)exponential function ex log(x)        natural logarithm ln(x), x>0.

log10(x)                          base 10 logarithm log10(x), x>0.

xy. A domain error occurs if x=0 and y<=0, or if x<0 and y is not an

pow(x,y)

integer.

sqrt(x)   sqare root of x, x>=0. ceil(x)        smallest integer not less than x, as a double. floor(x)largest integer not greater than x, as a double. fabs(x)absolute value |x|

ldexp(x,n)          x*2n

splits x into a normalized fraction in the interval [1/2,1) which is returned,

frexp(x, int *ip) and a power of 2, which is stored in *exp. If x is zero, both parts of the result are zero.

splits x into integral and fractional parts, each with the same sign as x. It

modf(x, double *ip)

stores the integral part in *ip, and returns the fractional part.

floating-point remainder of x/y, with the same sign as x. If y is zero, the

fmod(x,y) result is implementation-defined.

B.5 Utility Functions: <stdlib.h>

The header <stdlib.h>declares functions for number conversion, storage allocation, and similar tasks.

double atof(const char *s) atofconverts sto double; it is equivalent to strtod(s, (char**)NULL).

int atoi(const char *s)converts sto int; it is equivalent to (int)strtol(s, (char**)NULL, 10).

long atol(const char *s)converts sto long; it is equivalent to strtol(s, (char**)NULL, 10).

double strtod(const char *s, char **endp)

strtodconverts the prefix of sto double, ignoring leading white space; it stores a pointer to

any unconverted suffix in *endpunless endpis NULL. If the answer would overflow,

HUGE_VALis returned with the proper sign; if the answer would underflow, zero is returned. In either case errnois set to ERANGE.

long strtol(const char *s, char **endp, int base)

strtolconverts the prefix of sto long, ignoring leading white space; it stores a pointer to any unconverted suffix in *endpunless endpis NULL. If baseis between 2 and 36, conversion is done assuming that the input is written in that base. If baseis zero, the base is 8, 10, or 16; leading 0 implies octal and leading 0xor 0Xhexadecimal. Letters in either case represent digits from 10 to base-1; a leading 0xor 0Xis permitted in base 16. If the answer would overflow, LONG_MAXor LONG_MINis returned, depending on the sign of the result, and errnois set to ERANGE.

unsigned long strtoul(const char *s, char **endp, int base)

strtoulis the same as strtolexcept that the result is unsigned longand the error value is ULONG_MAX.

int rand(void)

randreturns a pseudo-random integer in the range 0 to RAND_MAX, which is at least 32767.

void srand(unsigned int seed)

sranduses seedas the seed for a new sequence of pseudo-random numbers. The initial seed is

1.

void *calloc(size_t nobj, size_t size)

callocreturns a pointer to space for an array of nobjobjects, each of size size, or NULLif the request cannot be satisfied. The space is initialized to zero bytes.

void *malloc(size_t size)

mallocreturns a pointer to space for an object of size size, or NULLif the request cannot be satisfied. The space is uninitialized.

void *realloc(void *p, size_t size)

reallocchanges the size of the object pointed to by pto size. The contents will be unchanged up to the minimum of the old and new sizes. If the new size is larger, the new space is uninitialized. reallocreturns a pointer to the new space, or NULLif the request cannot be satisfied, in which case *pis unchanged.

void free(void *p)

freedeallocates the space pointed to by p; it does nothing if pis NULL. pmust be a pointer to space previously allocated by calloc, malloc, or realloc.

void abort(void)abortcauses the program to terminate abnormally, as if by raise(SIGABRT).

void exit(int status)

exitcauses normal program termination. atexitfunctions are called in reverse order of registration, open files are flushed, open streams are closed, and control is returned to the environment. How statusis returned to the environment is implementation-dependent, but zero is taken as successful termination. The values EXIT_SUCCESSand EXIT_FAILUREmay also be used.

int atexit(void (*fcn)(void))

atexitregisters the function fcnto be called when the program terminates normally; it returns non-zero if the registration cannot be made.

int system(const char *s)

systempasses the string sto the environment for execution. If sis NULL, systemreturns nonzero if there is a command processor. If sis not NULL, the return value is implementationdependent.

char *getenv(const char *name)

getenvreturns the environment string associated with name, or NULLif no string exists. Details are implementation-dependent.

void *bsearch(const void *key, const void *base,               size_t n, size_t size,

              int (*cmp)(const void *keyval, const void *datum))

bsearchsearches base[0]...base[n-1]for an item that matches *key. The function cmpmust return negative if its first argument (the search key) is less than its second (a table entry), zero if equal, and positive if greater. Items in the array basemust be in ascending order. bsearchreturns a pointer to a matching item, or NULLif none exists.

void qsort(void *base, size_t n, size_t size,            int (*cmp)(const void *, const void *))

qsortsorts into ascending order an array base[0]...base[n-1]of objects of size size. The comparison function cmpis as in bsearch.

int abs(int n)

absreturns the absolute value of its intargument.

long labs(long n)

labsreturns the absolute value of its longargument.

div_t div(int num, int denom)

divcomputes the quotient and remainder of num/denom. The results are stored in the intmembers quotand remof a structure of type div_t.

ldiv_t ldiv(long num, long denom)

ldivcomputes the quotient and remainder of num/denom. The results are stored in the longmembers quotand remof a structure of type ldiv_t.

B.6 Diagnostics: <assert.h>

The assertmacro is used to add diagnostics to programs:

  void assert(int expression)

If expression is zero when

  assert(expression)

is executed, the assertmacro will print on stderra message, such as

  Assertion failed:expression, filefilename, linennn

It then calls abortto terminate execution. The source filename and line number come from the preprocessor macros __FILE__and __LINE__.

If NDEBUGis defined at the time <assert.h>is included, the assert macro is ignored.

B.7 Variable Argument Lists: <stdarg.h>

The header <stdarg.h>provides facilities for stepping through a list of function arguments of unknown number and type.

Suppose lastargis the last named parameter of a function fwith a variable number of arguments. Then declare within fa variable of type va_listthat will point to each argument in turn:

   va_list ap;

apmust be initialized once with the macro va_startbefore any unnamed argument is accessed:

 

  va_start(va_list ap, lastarg);

Thereafter, each execution of the macro va_argwill produce a value that has the type and value of the next unnamed argument, and will also modify apso the next use of va_argreturns the next argument:

  type va_arg(va_list ap, type);The macro

   void va_end(va_list ap);

must be called once after the arguments have been processed but before fis exited.

B.8 Non-local Jumps: <setjmp.h>

The declarations in <setjmp.h>provide a way to avoid the normal function call and return sequence, typically to permit an immediate return from a deeply nested function call.

int setjmp(jmp_buf env)

The macro setjmpsaves state information in envfor use by longjmp. The return is zero from a direct call of setjmp, and non-zero from a subsequent call of longjmp. A call to setjmpcan only occur in certain contexts, basically the test of if, switch, and loops, and only in simple relational expressions.

      if (setjmp(env) == 0)           /* get here on direct call */       else           /* get here by calling longjmp */

void longjmp(jmp_buf env, int val)

longjmprestores the state saved by the most recent call to setjmp, using the information saved in env, and execution resumes as if the setjmpfunction had just executed and returned the non-zero value val. The function containing the setjmpmust not have terminated. Accessible objects have the values they had at the time longjmpwas called, except that nonvolatileautomatic variables in the function calling setjmpbecome undefined if they were changed after the setjmpcall.

B.9 Signals: <signal.h>

The header <signal.h>provides facilities for handling exceptional conditions that arise during execution, such as an interrupt signal from an external source or an error in execution.

void (*signal(int sig, void (*handler)(int)))(int)

signaldetermines how subsequent signals will be handled. If handleris SIG_DFL, the implementation-defined default behavior is used, if it is SIG_IGN, the signal is ignored; otherwise, the function pointed to by handlerwill be called, with the argument of the type of signal. Valid signals

include

 

SIGABRT

abnormal termination, e.g., from abort

SIGFPE

arithmetic error, e.g., zero divide or overflow

SIGILL

illegal function image, e.g., illegal instruction

SIGINT

interactive attention, e.g., interrupt

SIGSEGV

illegal storage access, e.g., access outside memory limits

SIGTERM  termination request sent to this program

signalreturns the previous value of handlerfor the specific signal, or SIG_ERRif an error occurs.

When a signal sigsubsequently occurs, the signal is restored to its default behavior; then the signalhandler function is called, as if by (*handler)(sig). If the handler returns, execution will resume where it was when the signal occurred.

The initial state of signals is implementation-defined.

int raise(int sig)

raisesends the signal sigto the program; it returns non-zero if unsuccessful.

B.10 Date and Time Functions: <time.h>

The header <time.h>declares types and functions for manipulating date and time. Some functions process local time, which may differ from calendar time, for example because of time zone. clock_tand time_tare arithmetic types representing times, and struct tmholds the components of a calendar time:

int tm_sec; seconds after the minute (0,61) 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

tm_isdstis positive if Daylight Saving Time is in effect, zero if not, and negative if the information is not available.

clock_t clock(void)

clockreturns the processor time used by the program since the beginning of execution, or -1if unavailable. clock()/CLK_PER_SECis a time in seconds.

time_t time(time_t *tp)

timereturns the current calendar time or -1if the time is not available. If tpis not NULL, the return value is also assigned to *tp.

double difftime(time_t time2, time_t time1)difftimereturns time2-time1expressed in seconds.

time_t mktime(struct tm *tp)

mktimeconverts the local time in the structure *tpinto calendar time in the same representation used by time. The components will have values in the ranges shown. mktimereturns the calendar time or -1if it cannot be represented.

The next four functions return pointers to static objects that may be overwritten by other calls.

char *asctime(const struct tm *tp)

asctime*tpinto a string of the form

      Sun Jan  3 15:14:13 1988\n\0

char *ctime(const time_t *tp)

ctimeconverts the calendar time *tpto local time; it is equivalent to

      asctime(localtime(tp)) struct tm *gmtime(const time_t *tp)gmtimeconverts the calendar time *tpinto Coordinated Universal Time (UTC). It returns NULLif UTC is not available. The name gmtimehas historical significance.

struct tm *localtime(const time_t *tp)

localtimeconverts the calendar time *tpinto local time.

size_t strftime(char *s, size_t smax, const char *fmt, const struct tm

*tp)strftimeformats date and time information from *tpinto saccording to fmt, which is analogous to a printfformat. Ordinary characters (including the terminating '\0') are copied into s. Each %c is replaced as described below, using values appropriate for the local environment. No more than smaxcharacters are placed into s. strftimereturns the number of characters, excluding the '\0', or zero if more than smaxcharacters were produced.

%a abbreviated weekday name.

%A full weekday name.

%b abbreviated month name.

%B full month name.

%c local date and time representation.

%d day of the month (01-31).

%H hour (24-hour clock) (00-23).

%I hour (12-hour clock) (01-12).

%j day of the year (001-366).

%m month (01-12).

%M minute (00-59).

%p local equivalent of AM or PM.

%S second (00-61).

%U week number of the year (Sunday as 1st day of week) (00-53).

%w weekday (0-6, Sunday is 0).

%W week number of the year (Monday as 1st day of week) (00-53).

%x local date representation.

%X local time representation.

%y year without century (00-99).

%Y year with century.

%Z time zone name, if any.

%%  %

B.11 Implementation-defined Limits: <limits.h> and <float.h>

The header <limits.h>defines constants for the sizes of integral types. The values below are acceptable minimum magnitudes; larger values may be used.

                    CHAR_BIT   8                                              bits in a char

CHAR_MAX

UCHAR_MAXor SCHAR_MAX  maximum value of char

CHAR_MIN

0or SCHAR_MIN

maximum value of char

INT_MAX

32767

maximum value of int

INT_MIN

-32767

minimum value of int

LONG_MAX

2147483647

maximum value of long

LONG_MIN

-2147483647

minimum value of long

SCHAR_MAX

+127

maximum value of signed char

SCHAR_MIN

-127

minimum value of signed char

SHRT_MAX

+32767

maximum value of short

SHRT_MIN

-32767

minimum value of short

UCHAR_MAX

255

maximum value of unsigned char

UINT_MAX

65535

maximum value of unsigned int

ULONG_MAX

4294967295

maximum value of unsigned long

USHRT_MAX

65535

maximum value of unsigned short

The names in the table below, a subset of <float.h>, are constants related to floating-point arithmetic. When a value is given, it represents the minimum magnitude for the corresponding quantity. Each implementation defines appropriate values.

FLT_RADIX

2

radix of exponent, representation, e.g., 2, 16

FLT_ROUNDS

 

floating-point rounding mode for addition

FLT_DIG

6

decimal digits of precision

FLT_EPSILON

1E-5

smallest number x such that 1.0+x != 1.0

FLT_MANT_DIG 

 

number of base FLT_RADIXin mantissa

                       FLT_MAX        1E+37  maximum floating-point number

                       FLT_MAX_EXP          maximum n such that FLT_RADIXn-1is representable

                       FLT_MIN        1E-37 minimum normalized floating-point number

                       FLT_MIN_EXP           minimum n such that 10nis a normalized number

DBL_DIG

10

decimal digits of precision

DBL_EPSILON

1E-9

smallest number x such that 1.0+x != 1.0

DBL_MANT_DIG

 

number of base FLT_RADIXin mantissa

DBL_MAX

1E+37

maximum doublefloating-point number

DBL_MAX_EXP

 

maximum n such that FLT_RADIXn-1is representable

DBL_MIN

1E-37

minimum normalized doublefloating-point number

DBL_MIN_EXP

 

minimum n such that 10nis a normalized number

Computer Courses

Get in touch with us

FIZIKA MIND

Best website developer in bareilly

Contact us

FIZIKA MIND.

Kipps Enclave Shastri Nagar Bareilly, IN

Cont. no. +91-9259436235
[email protected]

Join our mailing list

Signup for Our Free Newsletter
Education - This is a contributing Drupal Theme
Design by WeebPal.