==========
  STDLIB.H
 ==========
 Functions
 =========
  abort       
  abs         
  atexit      
  atof        
  atoi        
  atol        
  bsearch     
  calloc      
  div         
  ecvt        
  exit        
  _exit       
  fcvt        
  free        
  _fullpath   
  gcvt        
  getenv      
  itoa        
  labs        
  ldiv        
  lfind       
  _lrotl      
  _lrotr      
  lsearch     
  ltoa        
  _makepath   
  malloc      
  max         
  mblen       
  mbtowc      
  mbstowcs    
  min         
  putenv      
  qsort       
  rand        
  random      
  randomize   
  realloc     
  _rotl       
  _rotr       
  _searchenv  
  _splitpath  
  srand       
  strtod      
  strtol      
  _strtold    
  strtoul     
  swab        
  system      
  time        
  ultoa       
  wctomb      
  wcstombs    

 Constants, data types, and global variables
 ===========================================
  div_t       
  _doserrno   
  environ     
  errno       
  EXIT_FAILURE
  EXIT_SUCCESS
  _fmode      
  ldiv_t      
  NULL        
  _osmajor    
  _osminor    
  _psp        
  RAND_MAX    
  size_t      
  sys_errlist 
  sys_nerr    
  _version    
  wchar_t     

 See Also
 ========
  List of all Header files


========= ERRNO.H ========= Constants, data types, and global variables =========================================== _doserrno errno _sys_nerr error number definitions See Also ======== List of all Header files
========== LOCALE.H ========== Declares functions that provide information specific to languages and countries. Functions ========= localeconv setlocale Constants, data types, and global variables =========================================== __cplusplus LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME lconv (struct) NULL See Also ======== List of all Header files
========== STDARG.H ========== Macros ====== va_arg va_end va_start Constants, data types, and global variables =========================================== va_list See Also ======== List of all Header files
========== STDDEF.H ========== Constants, data types, and global variables =========================================== NULL ptrdiff_t size_t wchar_t See Also ======== List of all Header files
========== VALUES.H ========== Defines UNIX compatible constants for limits to float and double values. BITSPERBYTE DMAXEXP DMAXPOWTWO DMINEXP DSIGNIF FMAXEXP FMAXPOWTWO FMINEXP FSIGNIF _FEXPLEN HIBITI HIBITL HIBITS _LENBASE MAXDOUBLE MAXFLOAT MAXINT MAXLONG MAXSHORT MINDOUBLE MINFLOAT See Also ======== List of all Header files
========== SEARCH.H ========== Functions ========= bsearch lfind lsearch qsort
EXIT_xxxx <STDLIB.H> =========== Constants defining exit conditions for calls to the exit function. Name | Meaning --------------+---------------------------- EXIT_SUCCESS | Normal program termination EXIT_FAILURE | Abnormal program termination
RAND_MAX <STDLIB.H> ========== Maximum value returned by rand function.
div_t and ldiv_t <STDLIB.H> ================== The div_t type is a structure of integers used by div. typedef struct { long int quot; /* quotient */ long int rem; /* remainder */ } div_t; The ldiv_t type is a structure of longs used by ldiv. typedef struct { long int quot; /* quotient */ long int rem; /* remainder */ } ldiv_t;
atexit_t <STDLIB.H> ========== Type of exit function passed to atexit. typedef void (* atexit_t)(void);
sys_errlist <STDLIB.H> ============= Array of message strings Declaration: char *sys_errlist[] This is an array of message strings corresponding to errno and is used by the function perror. The mnemonics and their meanings for the values stored in sys_errlist are: Mnemonic | Meaning ---------+------------------------------- E2BIG | Arg list too long EACCES | Permission denied EBADF | Bad file number ECONTR | Memory blocks destroyed ECURDIR | Attempt to remove CurDir EDOM | Domain error EEXIST | File already exists EFAULT | Unknown error EINVACC | Invalid access code EINVAL | Invalid argument EINVDAT | Invalid data EINVDRV | Invalid drive specified EINVENV | Invalid environment EINVFMT | Invalid format EINVFNC | Invalid function number EINVMEM | Invalid memory block address EMFILE | Too many open files ENMFILE | No more files ENODEV | No such device ENOENT | No such file or directory ENOEXEC | Exec format error ENOFILE | No such file or directory ENOMEM | Not enough memory ENOPATH | Path not found ENOTSAM | Not same device ERANGE | Result out of range EXDEV | Cross-device link EZERO | Error 0 See Also: _doserrno errno sys_nerr List of all global variables
sys_nerr <STDLIB.H> ========== Number of error message strings Declaration: extern int sys_nerr This variable contains the number of error message strings in sys_errlist. See Also: List of all global variables
======= abort <STDLIB.H, PROCESS.H> ======= Abnormally terminates a process Declaration: void abort(void); Remarks: abort writes a termination message on stderr ("Abnormal program termination"), then aborts the program by a call to _exit with exit code 3. Return Value: Returns exit code 3 to the parent process or to DOS Portability: + DOS + UNIX + Windows + ANSI C + C++ only + | Yes | Yes | Yes | Yes | No | +-----+------+---------+--------+----------+ See Also: _exit assert atexit exit raise signal spawn Example: #include <stdio.h> #include <stdlib.h> int main(void) { printf("Calling abort()\n"); abort(); return 0; /* This is never reached */ }
======== atexit <STDLIB.H> ======== Registers termination function Declaration: int atexit(atexit_t func); Remarks: atexit registers the function pointed to by func as an exit function. Upon normal termination of the program, exit calls (*func)() just before returning to the operating system. Each call to atexit registers another exit function. Up to 32 functions can be registered. They are executed on a last-in, first-out basis (the last function registered is the first to be executed). Return Value * On success, returns 0 * On error, returns non-zero (no space left to register the function) Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: abort _exit exit spawn Example: #include <stdio.h> #include <stdlib.h> void exit_fn1(void) { printf("Exit function #1 called\n"); } void exit_fn2(void) { printf("Exit function #2 called\n"); } int main(void) { /* post exit function #1 */ atexit(exit_fn1); /* post exit function #2 */ atexit(exit_fn2); return 0; }
====== atoi <STDLIB.H> ====== Macro that converts string to integer Declaration: int atoi(const char *s); Remarks: atoi converts a string pointed to by s to int. atoi recognizes (in the following order) * an optional string of tabs and spaces * an optional sign * a string of digits The characters must match this format: [ws] [sn] [ddd] In atoi, the first unrecognized character ends the conversion. There are no provisions for overflow in atoi (results are undefined). Return Value: * On success, returns the converted value of the input string. * If the string can't be converted, returns 0. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: atof atol ecvt fcvt gcvt scanf strtod Example: #include <stdlib.h> #include <stdio.h> int main(void) { int n; char *str = "12345.67"; n = atoi(str); printf("string = %s integer = %d\n", str, n); return 0; }
====== atol <STDLIB.H > ====== Converts a string to a long Declaration: long atol(const char *s); Remarks: atol converts the string pointed to by s to long. atol recognizes (in the following order) * an optional string of tabs and spaces [ws] * an optional sign [sn] * a string of digits [ddd] The characters must match this format: [ws] [sn] [ddd] In atol, the first unrecognized character ends the conversion. There are no provisions for overflow in atol (results are undefined). Return Value: * On success, returns the converted value of the input string. * If the string can't be converted, returns 0. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: atof atoi ecvt fcvt gcvt scanf strtod strtol strtoul Example: #include <stdlib.h> #include <stdio.h> int main(void) { long l; char *lstr = "98765432"; l = atol(lstr); printf("string = %s integer = %ld\n", lstr, l); return(0); }
==================== bsearch, lfind, lsearch, and qsort <STDLIB.H, SEARCH.H> ==================== * bsearch performs a binary search * lfind and lsearch perform a linear search * qsort sorts using the quicksort algorithm Declaration: * void *bsearch(const void *key, const void *base, size_t nelem, size_t width, int (*fcmp)(const void*, const void*)); * void *lfind(const void *key, const void *base, size_t *num, size_t width, int (*fcmp)(const void *, const void*)); * void *lsearch(const void *key, void *base, size_t *num, size_t width, int (*fcmp)(const void *, const void *)); * void qsort(void *base, size_t nelem, size_t width, int (*fcmp)(const void *, const void *)); Remarks: Function| What It Does ---------+-------------------------------------------------------------- bsearch | Makes a binary search for the value *key in a table (array) | of nelem elements in memory lfind | Makes a linear search for *key in an array of sequential | records lsearch | Makes a linear search for *key in a table. If *key is not in | the table, lsearch appends it (the search key) to the table. qsort | Is an implementation of the "median of three" variant of the | quicksort algorithm Argument| What It Is/Points To ---------+----------------------------------------------------------- base | The base (0th element) of the search table fcmp | A user-defined comparison routine that compares two items | and returns a value based on the comparison key | The item to be searched for (the search key) nelem | The number of entries in the table num | The number of entries in the table width | The number of bytes in each entry NOTE: * Because lsearch performs a linear search, the table entries do not need to be sorted before the function call. * Because bsearch performs a binary search, the first matching entry is not necessarily the first entry in the table. Return Value: Function| On Failure | On Success ---------+----------------+-------------------------- bsearch | 0 (No match) | The address of the first lfind | NULL (No match)| entry in the table that lsearch | | matches the search key ---------+----------------+-------------------------- qsort | None | None Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + bsearch | Yes | Yes | Yes | Yes | | lfind | Yes | Yes | Yes | | | lsearch | Yes | Yes | Yes | | | qsort | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ Examples: bsearch example lfind example lsearch example qsort example
bsearch example ================= #include <stdlib.h> #include <stdio.h> typedef int (*fptr)(const void*, const void*); #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) int numarray[] = {123, 145, 512, 627, 800, 933}; int numeric (const int *p1, const int *p2) { return(*p1 - *p2); } #pragma argsused int lookup(int key) { int *itemptr; /* The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at compile time */ itemptr = (int *) bsearch (&key, numarray, NELEMS(numarray), sizeof(int), (fptr)numeric); return (itemptr != NULL); } int main(void) { if (lookup(512)) printf("512 is in the table.\n"); else printf("512 isn't in the table.\n"); return 0; }
lfind example =============== #include <stdio.h> #include <stdlib.h> int compare(int *x, int *y) { return( *x - *y ); } int main(void) { int array[5] = {35, 87, 46, 99, 12}; size_t nelem = 5; int key; int *result; key = 99; result = (int *) lfind(&key, array, &nelem, sizeof(int), (int(*)(const void *,const void *))compare); if (result) printf("Number %d found\n",key); else printf("Number %d not found\n",key); return 0; }
lsearch example ================= /* lsearch example */ #include <stdlib.h> #include <stdio.h> #include <string.h> /* for strcmp declaration */ /* initialize number of colors */ char *colors[10] = { "Red", "Blue", "Green" }; int ncolors = 3; int colorscmp(char **arg1, char **arg2) { return(strcmp(*arg1, *arg2)); } int addelem(char *key) { int oldn = ncolors; lsearch(key, colors, (size_t *)&ncolors, sizeof(char *), (int(*)(const void *,const void *))colorscmp); return(ncolors == oldn); } int main(void) { int i; char *key = "Purple"; if (addelem(key)) printf("%s already in colors table\n", key); else { strcpy(colors[ncolors-1],key); printf("%s added to colors table\n", key); } printf("The colors:\n"); for (i = 0; i < ncolors; i++) printf("%s\n", colors[i]); return 0; }
qsort example =============== #include <stdio.h> #include <stdlib.h> #include <string.h> int sort_function( const void *a, const void *b); char list[5][4] = { "cat", "car", "cab", "cap", "can" }; int main(void) { int x; qsort((void *)list, 5, sizeof(list[0]), sort_function); for (x = 0; x < 5; x++) printf("%s\n", list[x]); return 0; } int sort_function( const void *a, const void *b) { return( strcmp((char *)a,(char *)b) ); }
======== calloc <STDLIB.H, ALLOC.H) ======== Allocates main memory Declaration: void *calloc(size_t nitems, size_t size); Remarks: calloc provides access to the C memory heap, which is available for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation. calloc allocates a block (nitems * size) bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc. Small Data Models ================= All the space between the end of the data segment and the top of the program stack is available for use in the tiny, small, and medium models, except for a small margin immediately before the top of the stack. This margin allows room for the application to grow on the stack, plus a small amount needed by DOS. Large Data Models ================= In the compact, large, and huge models, all space beyond the program stack to the end of physical memory is available for the heap. Return Value: * On success, returns a pointer to the newly allocated block. * On failure (not enough space exists for the new block, or nitems or size is 0), returns null. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: free malloc realloc Example: #include <stdio.h> #include <alloc.h> #include <string.h> int main(void) { char *str = NULL; /* allocate memory for string */ str = (char *) calloc(10, sizeof(char)); /* copy "Hello" into string */ strcpy(str, "Hello"); /* display string */ printf("String is %s\n", str); /* free memory */ free(str); return 0; }
=========== div, ldiv <STDLIB.H> =========== * div divides two integers * ldiv divides two longs Declaration: * div_t div(int numer, int denom); * ldiv_t ldiv(long int numer, long int denom); Remarks: div divides two integers and returns both the quotient and the remainder as a div_t type. ldiv divides two longs and returns both the quotient and the remainder as an ldiv_t type. Arg. | What It Is -------+------------- numer | numerator denom | denominator Return Value: Both functions return a structure whose elements are quot (the quotient) and rem (the remainder). Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | Yes | | +-----+------+---------+--------+----------+ Examples: div example ldiv example
div example ============= /* div example */ #include <stdlib.h> #include <stdio.h> div_t x; int main(void) { x = div(10,3); printf("10 div 3 = %d remainder %d\n", x.quot, x.rem); return 0; }
ldiv example ============== /* ldiv example */ #include <stdlib.h> #include <stdio.h> int main(void) { ldiv_t lx; lx = ldiv(100000L, 30000L); printf("100000 div 30000 = %ld remainder %ld\n", lx.quot, lx.rem); return 0; }
=============== ecvt and fcvt <STDLIB.H> =============== Convert floating-point number to string Declaration: * char *ecvt(double value, int ndig, int *dec, int *sign); * char *fcvt(double value, int ndig, int *dec, int *sign); Remarks: ecvt and fcvt convert value to a null-terminated string of ndig digits, starting with the leftmost significant digit, and return a pointer to the string. The position of the decimal point relative to the beginning of the string is stored indirectly through dec. If dec < 0, the decimal lies to the left of the returned digits. There is no decimal point in the string itself. If value < 0, the word *sign is non-zero. Otherwise, the word is 0. * In ecvt, the low-order digit is rounded. * In fcvt, the correct digit is rounded for the number of digits specified by ndig. Return Value: * ecvt: Points to static data for the string of digits whose content is overwritten by each call to ecvt. * fcvt: Points to static data whose content is overwritten by each call to fcvt. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | | | +-----+------+---------+--------+----------+ See Also: gcvt Examples: ecvt example fcvt example
ecvt example ============== #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { char *string; double value; int dec, sign; int ndig = 10; clrscr(); value = 9.876; string = ecvt(value, ndig, &dec, &sign); printf("string = %s dec = %d sign = %d\n", string, dec, sign); value = -123.45; ndig= 15; string = ecvt(value,ndig,&dec,&sign); printf("string = %s dec = %d sign = %d\n", string, dec, sign); value = 0.6789e5; /* scientific notation */ ndig = 5; string = ecvt(value,ndig,&dec,&sign); printf("string = %s dec = %d sign = %d\n", string, dec, sign); return 0; }
fcvt example ============== #include <stdlib.h> #include <stdio.h> int main(void) { char *str; double num; int dec, sign, ndig = 5; /* a regular number */ num = 9.876; str = fcvt(num, ndig, &dec, &sign); printf("string = %10s decimal place = %d sign = %d\n", str, dec, sign); /* a negative number */ num = -123.45; str = fcvt(num, ndig, &dec, &sign); printf("string = %10s decimal place = %d sign = %d\n", str, dec, sign); /* scientific notation */ num = 0.678e5; str = fcvt(num, ndig, &dec, &sign); printf("string = %10s decimal place= %d sign = %d\n", str, dec, sign); return 0;
=========== _fullpath <STDLIB.H> =========== Converts a path name from relative to absolute Declaration: char * _fullpath(char *buffer, const char *path, int buflen); Remarks _fullpath converts the relative path name in path to an absolute path name and stores it in an array of characters. Argument| What It Is, Does --------+------------------------------------------------------------------ buffer | Points to array of characters where absolute path name is stored buflen | Maximum number of characters that can be stored at buffer path | Relative path name to be converted to absolute _fullpath returns NULL if the buffer isn't big enough to store the absolute path name, or if the path contains an invalid drive letter. If buffer is NULL, _fullpath allocates a buffer of up to _MAX_PATH characters (defined in STDLIB.H). When this buffer is no longer needed, use free to free it. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ Return Value * On success, returns a pointer to the buffer containing the absolute path name * On error, returns NULL. See Also: _makepath _splitpath Example: #include <stdio.h> #include <stdlib.h> char buf[_MAX_PATH]; void main(int argc, char *argv[]) { for ( ; argc; argv++, argc--) { if (_fullpath(buf, argv[0], _MAX_PATH) == NULL) printf("Unable to obtain full path of %s\n",argv[0]); else printf("Full path of %s is %s\n",argv[0],buf); } }
====== gcvt <STDLIB.H> ====== Converts a floating-point number to a string Declaration: char *gcvt(double value, int ndec, char *buf); Remarks: gcvt converts value to a null-terminated ASCII string and stores the string in buf. It produces ndec significant digits in FORTRAN F format, if possible. Otherwise, it returns the value in the printf E format (ready for printing). gcvt might suppress trailing zeros. Return Value: * On success, returns the address of the string *buf. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | | | +-----+------+---------+--------+----------+ See Also: ecvt fcvt sprintf Example: #include <stdlib.h> #include <stdio.h> int main(void) { char str[25]; double num; int sig = 5; /* significant digits */ /* a regular number */ num = 9.876; gcvt(num, sig, str); printf("string = %s\n", str); /* a negative number */ num = -123.4567; gcvt(num, sig, str); printf("string = %s\n", str); /* scientific notation */ num = 0.678e5; gcvt(num, sig, str); printf("string = %s\n", str); return(0); }
================ getenv, putenv <STDLIB.H> ================ * getenv gets a string from the environment * putenv adds a string to the current environment Declaration: * char *getenv(const char *name); * int putenv(const char *name); Remarks: * getenv returns the value of a specified variable. * putenv accepts the string "name" and adds it to the environment of the current process. name can be either uppercase or lowercase. Environment entries must not be changed directly. If you want to change an environment value, you must use putenv. You can also use putenv to modify or delete an existing name. To delete an existing entry, make the variable value empty: for example, MYVAR= You can only use putenv to modify the current program's environment. Once the program ends, the old environment is restored. The string given to putenv must be static or global. Unpredictable results will occur if a local or dynamic string given to putenv is used after the string memory is released. Return Value: * On success, * getenv returns the value associated with name. * putenv returns 0. * On error, * getenv returns a NULL pointer (if the specified name is not defined in the environment) * putenv returns -1 Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + getenv | Yes | Yes | Yes | Yes | | putenv | Yes | Yes | Yes | | | +-----+------+---------+--------+----------+ See Also: environ getpsp Example (for both functions): #include <stdio.h> #include <stdlib.h> #include <alloc.h> #include <string.h> #include <dos.h> int main(void) { char *path, *ptr; int i = 0; /* get the current path environment */ ptr = getenv("PATH"); /* set up new path */ path = (char *) malloc(strlen(ptr)+15); strcpy(path,"PATH="); strcat(path,ptr); strcat(path,";c:\\temp"); /* replace the current path and display current environment */ putenv(path); while (environ[i]) printf("%s\n",environ[i++]); return 0; }
=================== itoa, ltoa, ultoa <STDLIB.H> =================== * itoa converts an integer to a string * ltoa converts a long to a string * ultoa converts an unsigned long to a string Declaration: * char *itoa(int value, char *string, int radix); * char *ltoa(long value, char *string, int radix); * char *ultoa(unsigned long value, char *string, int radix); Remarks: itoa, ltoa, and ultoa convert value to a null-terminated string and store the result in string. Arg. | Function | What Argument Is/Does --------+----------+--------------------------------------------------- value | itoa | Integer to be converted value | ltoa | Long integer to be converted value | ultoa | Unsigned long to be converted string | (all 3) | Points to location where converted number and | | terminating null character (\0) are stored. radix | (all 3) | Specifies the base to be used in converting value | | radix must be between 2 and 36, inclusive. If value is negative and radix is 10, itoa and ltoa set the first character of string to the minus sign (ultoa does not). ultoa performs no overflow checking. The space allocated for string must be large enough to hold the returned string, including the terminating null character (\0). itoa can return up to 17 bytes; ltoa and ultoa can return up to 33 bytes. Return Value: * On success, these functions return a pointer to the target string. * On error: There is no error return. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ Examples: itoa example ltoa example ultoa example
itoa example ============== #include <stdlib.h> #include <stdio.h> int main(void) { int number = 12345; char string[25]; itoa(number, string, 10); printf("integer = %d string = %s\n", number, string); return 0; }
ltoa example ============== #include <stdlib.h> #include <stdio.h> int main(void) { char string[25]; long value = 123456789L; ltoa(value,string,10); printf("number = %ld string = %s\n", value, string); return 0; }
ultoa example =============== #include <stdlib.h> #include <stdio.h> int main( void ) { unsigned long lnumber = 3123456789L; char string[25]; ultoa(lnumber,string,10); printf("string = %s unsigned long = %lu\n",string,lnumber); return 0; }
==================== _lrotl and _lrotr, <STDLIB.H> _rotl and _rotr ==================== * _lrotl rotates an unsigned long value to the left * _lrotr rotates an unsigned long value to the right * _rotl rotates an unsigned integer value to the left * _rotr rotates an unsigned integer value to the right Declaration: * unsigned long _lrotr(unsigned long val, int count); * unsigned long _lrotl(unsigned long val, int count); * unsigned _rotl(unsigned val, int count); * unsigned _rotr(unsigned val, int count); Remarks: * _lrotl rotates val to the left by count bits * _lrotr rotates val to the right by count bits * _rotl rotates val to the left by count bits. * _rotr rotates val to the right by count bits. For the _lrot... functions, the value rotated is an unsigned long; for the _rot... functions, the value is an unsigned integer. Return Value: * _lrotl: val left-rotated by count bits * _lrotr: val right-rotated by count bits * _rotl: val left-rotated by count bits * _rotr: val right-rotated by count bits Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ Examples _lrotl/_lrotr example _rotl/_rotr example
_lrotl and _lrotr example =========================== #include <stdlib.h> #include <stdio.h> /* function prototypes */ int lrotl_example(void); int lrotr_example(void); /* lrotl example */ int lrotl_example(void) { unsigned long result; unsigned long value = 100; result = _lrotl(value,1); printf("The value %lu rotated left one bit is: %lu\n", value, result); return 0; } /* lrotr example */ int lrotr_example(void) { unsigned long result; unsigned long value = 100; result = _lrotr(value,1); printf("The value %lu rotated right one bit is: %lu\n", value, result); return 0; } int main(void) { lrotl_example(); lrotr_example(); return 0; }
_rotl and _rotr example ========================= #include <stdlib.h> #include <stdio.h> /* rotl example */ int rotl_example(void) { unsigned value, result; value = 32767; result = _rotl(value, 1); printf("The value %u rotated left one bit is: %u\n", value, result); return 0; } /* rotr example */ int rotr_example(void) { unsigned value, result; value = 32767; result = _rotr(value, 1); printf("The value %u rotated right one bit is: %u\n", value, result); return 0; } int main(void) { rotl_example(); rotr_example(); return 0; }
======================= _makepath, _splitpath <STDLIB.H> fnmerge, fnsplit <DIR.H> ======================= * _makepath and fnmerge build a path from component parts * _splitpath and fnsplit split a full path name into its components Syntax: * void _makepath(char *path, const char *drive, const char *dir, const char *name, const char *ext); * void fnmerge (char *path, const char *drive, const char *dir, const char *name, const char *ext); * void _splitpath(const char *path, char *drive, char *dir, char *name, char *ext); * int fnsplit (const char *path, char *drive, char *dir, char *name, char *ext); Remarks * _makepath and fnmerge make a full path name from components. * _splitpath and fnsplit take a file's full path name as a string, split the name into its four components, then store those components. _makepath and _splitpath are invertible; if you split a given path with _splitpath, then merge the resultant components with _makepath, you end up with that same path. Likewise, fnmerge and fnsplit are invertible. If you split a given path with fnsplit, then merge the resultant components with fnmerge, you end up with path. Arg. | Function | What Argument Is/Does -------+------------+----------------------------------------------------- path | _makepath | New path name, X:\DIR\SUBDIR\NAME.EXT drive | and | X: (disk drive) part of new path name dir | fnmerge | \DIR\SUBDIR\ (directory) part of new path name name | | NAME (file name) part of new path name ext | | .EXT (extension) part of new path name -------+------------+----------------------------------------------------- path | _splitpath | Original path name, "X:\DIR\SUBDIR\NAME.EXT" drive | and | Points to string where "X:" (disk drive) is stored dir | fnsplit | Points to string where "\DIR\SUBDIR\" (directory) | | is stored name | | Points to string where "NAME" (file name) is stored ext | | Points to string where ".EXT" (extension) is stored _makepath and fnmerge assume there is enough space in path for the constructed path name. If... | _makepath inserts --------------------------------------------+------------------------------ drive is empty or NULL | No drive in the path name drive is missing a trailing colon (:) | A colon in the path name dir is empty or NULL | No directory in the path name dir is missing a trailing slash (\ or /) | A backslash in the path name name is empty or NULL | No file name in the path name ext is empty or NULL | No extension in the path name ext is missing a leading period (.) | A period in the path name _splitpath and fnsplit assume there is enough space to store each non-null component. All five components must be passed to _splitpath and fnsplit, but any of them can be a null, which means the corresponding component will be parsed but not stored. Maximum Sizes ============= The maximum sizes for the arguments to _splitpath and fnsplit include space for the null-terminator. _MAX_... constants are defined in STDLIB.H; the MAX... constants are defined in DIR.H. |_splitpath|fnsplit |Max.| Arg. |constant |constant|Size| Comments ------+----------+--------+----+-------------------------------------------- path |_MAX_PATH |MAXPATH | 80 | --- drive|_MAX_DRIVE|MAXDRIVE| 3 | Includes colon (:) dir |_MAX_DIR |MAXDIR | 66 | Includes leading, trailing backslashes (\) name |_MAX_FNAME|MAXFNAME| 9 | --- ext |_MAX_EXT |MAXEXT | 5 | Includes leading dot (.) Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ Return Value: * _makepath, _splitpath, and fnmerge do not return * fnsplit returns an integer (composed of five flags, defined in DIR.H) indicating which of the full path name components were present in path. See Also: _fullpath Examples: _makepath example _splitpath example fnmerge example fnsplit example
_makepath example =================== #include <dir.h> #include <string.h> #include <stdio.h> #include <stdlib.h> int main(void) { char s[_MAX_PATH]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char file[_MAX_FNAME]; char ext[_MAX_EXT]; getcwd(s,_MAX_PATH); /* get current working directory */ if (s[strlen(s)-1] != '\\') strcat(s,"\\"); /* append a trailing \ character */ _splitpath(s,drive,dir,file,ext); /* @$split the string to separate elems */ strcpy(file,"DATA"); strcpy(ext,".TXT"); _makepath(s,drive,dir,file,ext); /* @$merge everything into one string */ puts(s); /* display resulting string */ return 0; }
_splitpath example =================== #include <dir.h> #include <string.h> #include <stdio.h> #include <stdlib.h> int main(void) { char s[_MAX_PATH]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char file[_MAX_FNAME]; char ext[_MAX_EXT]; /* get current working directory */ getcwd(s,_MAX_PATH); if (s[strlen(s)-1] != '\\') /* append a trailing \ character */ strcat(s,"\\"); /* split the string to separate elems */ _splitpath(s,drive,dir,file,ext); strcpy(file,"DATA"); strcpy(ext,".TXT"); /* merge everything into one string */ _makepath(s,drive,dir,file,ext); /* display resulting string */ puts(s); return 0; }
fnsplit example ================= #include <stdlib.h> #include <stdio.h> #include <dir.h> int main(void) { char *s; char drive[MAXDRIVE]; char dir[MAXDIR]; char file[MAXFILE]; char ext[MAXEXT]; int flags; s=getenv("COMSPEC"); /* get the comspec environment parameter */ flags=fnsplit(s,drive,dir,file,ext); printf("Command processor info:\n"); if(flags & DRIVE) printf("\tdrive: %s\n",drive); if(flags & DIRECTORY) printf("\tdirectory: %s\n",dir); if(flags & FILENAME) printf("\tfile: %s\n",file); if(flags & EXTENSION) printf("\textension: %s\n",ext); return 0; }
fnmerge example ================= #include <string.h> #include <stdio.h> #include <dir.h> int main(void) { char s[MAXPATH]; char drive[MAXDRIVE]; char dir[MAXDIR]; char file[MAXFILE]; char ext[MAXEXT]; getcwd(s,MAXPATH); /* get the current working directory */ strcat(s,"\\"); /* append on a trailing character */ fnsplit(s,drive,dir,file,ext); /* split the string to separate elems */ strcpy(file,"DATA"); strcpy(ext,".TXT"); fnmerge(s,drive,dir,file,ext); /* merge everything into one string */ puts(s); /* display resulting string */ return 0; }
========== max, min <STDLIB.H> ========== * max returns the larger of two values * min returns the smaller of two values Declaration: * (type) max(a, b); * (type) min(a, b); Remarks: max and min are macros that generate inline code to find the maximum or minimum value of two values. Both arguments and the function declaration must be of the same type. Return Value: * max returns the larger of two values. * min returns the smaller of two values. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ Example (for both macros): /* max example */ #include <stdlib.h> #include <stdio.h> #ifdef __cplusplus int max (int value1, int value2); int max(int value1, int value2) { return ( (value1 > value2) ? value1 : value2); } #endif int main(void) { int x = 5; int y = 6; int z; z = max(x, y); printf("The larger number is %d\n", z); return 0; }
======= mblen <STDLIB.H> ======= Determines the length of a multibyte character Declaration: int mblen(const char *s, size_t n); Remarks: If s is not NULL, mblen determines the length of the multibyte character *s. Arg| What It Is/Does ---+------------------------------------------------------ n | Specifies the maximum number of bytes to be examined s | Points to multibyte character (if not NULL) The LC_CTYPE setting of the current locale affects the behavior of mblen. Return Value: Value | mblen | of s | Returns | If ... -------+----------+-------------------------------------------------------- NULL | non-zero | Multibyte characters have state-dependent encodings | 0 | Multibyte characters do not have state-dependent | | encodings -------+----------+-------------------------------------------------------- not | 0 | s points to the null character NULL | -1 | The next n bytes do not comprise a valid multibyte | | character; the number of bytes that comprise a valid | | multibyte charter. Portability: + DOS + UNIX + Windows + ANSI C + C++ only + | yes | | yes | | yes | +-----+------+---------+--------+----------+ See Also: mbtowc mbstowc setlocale
===================== mbstowcs and mbtowc <STDLIB.H> ===================== * mbstowcs converts a multibyte string to a wchar_t array * mbtowc converts a multibyte character to wchar_t code Declaration: * size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n); * int mbtowc(wchar_t *pwc, const char *s, size_t n); Remarks * mbstowcs converts the multibyte string s into the array *pwcs. No more than n values are stored in the array. If mbstowcs encounters an invalid multibyte sequence, it returns (size_t - 1). The pwcs array will not be terminated with a 0 value if mbstowcs returns n. * If s is not null, mbtowc determines the number of bytes that comprise the multibyte character *s. mbtowc then determines the value of the type wchar_t that corresponds to that multibyte character. If there is a successful match between wchar_t and the multibyte character, and pwc is not null, mbtowc stores the wchar_t value in the array *pwc. At most n characters are examined. Return Value: * mbstowcs * If mbstowcs encounters an invalid multibyte sequence, it returns (size_t - 1). * Otherwise, it returns the number of array elements modified, not including the terminating code, if any. * mbtowc * When s points to an invalid multibyte character, mbtowc returns -1. * When s points to the NULL character, mbtowc returns 0. * Otherwise, mbtowc returns the number of bytes that comprise the converted multibyte character. The return value will never exceed MB_CUR_MAX or the value of n. Portability: + DOS + UNIX + Windows + ANSI C + C++ only + | yes | | yes | yes | | +-----+------+---------+--------+----------+ See Also: mblen setlocale
====== rand <STDLIB.H> ====== Random number generator Declaration: int rand(void); Remarks: rand uses a multiplicative congruential random number generator with period 232 to return successive pseudo-random numbers in the range 0 to RAND_MAX. Return Value: rand returns the generated pseudo-random number. Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: random randomize srand Example: #include <stdlib.h> #include <stdio.h> int main(void) { int i; printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; }
======== random <STDLIB.H> ======== Macro that returns an integer Declaration: * Macro: random(num); * Function: int random(int num); Remarks: random returns a random number between 0 and (num-1). random(num) is a macro defined in STDLIB.H. Return Value: Returns an integer between 0 and (num - 1). Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ See Also: rand randomize srand Example: #include <stdlib.h> #include <stdio.h> #include <time.h> /* prints a random number in the range 0 to 99 */ int main(void) { randomize(); printf("Random number in the 0-99 range: %d\n", random (100)); return 0; }
=========== randomize <STDLIB.H> =========== Macro that initializes random number generator Declaration: * void randomize(void); Remarks: randomize initializes the random number generator with a random value. Because randomize is implemented as a macro that calls the time function prototyped in TIME.H, you should include TIME.H when you use this routine. Return Value: None Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ See Also: rand random srand Example: #include <stdlib.h> #include <stdio.h> #include <time.h> int main(void) { int i; randomize(); printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; }
============ _searchenv <STDLIB.H> ============ Searches an environment path for a file. Declaration: char *_searchenv(const char *file, const char *varname, char *buf); Remarks: _searchenv attempts to locate a file, searching along the path specified by a DOS environment variable. Argument | What It Is/Does ----------+---------------------------------------------------------------- file | File that _searchenv attempts to locate varname | DOS environment variable (Typical environment variables | containing paths are PATH, LIB, and INCLUDE.) buf | Points to a buffer where _searchenv stores the full path name | of the located file. _searchenv assumes *buf is large enough | to store any possible file name. _searchenv first searches for the file in the current directory of the current drive. If the file is not found there, _searchenv fetches varname, then searches each directory in the path it specifies, in turn, until either the file is found or the path is exhausted. When it locates the file, _searchenv stores the full path name in *buf. This full path name string can be used in a call to access the file (for example, with fopen or an exec function). If _searchenv can't successfully locate the file, it stores an empty string (consisting of only a null character) in *buf. Return Value: None Portability + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | | | +-----+------+---------+--------+----------+ See Also: _dos_findfirst _dos_findnext spawn... system Example: #include <stdio.h> #include <stdlib.h> char buf[_MAX_PATH]; int main(void) { /* looks for TLINK */ _searchenv("TLINK.EXE","PATH",buf); if (buf[0] == '\0') printf("TLINK.EXE not found\n"); else printf("TLINK.EXE found in %s\n", buf); /* looks for non-existent file */ _searchenv("NOTEXIST.FIL","PATH",buf); if (buf[0] == '\0') printf("NOTEXIST.FIL not found\n"); else printf("NOTEXIST.FIL found in %s\n", buf); return 0; } /* Program output TLINK.EXE found in C:\BIN\TLINK.EXE NOTEXIST.FIL not found */
======= srand <STDLIB.H> ======= Initializes random number generator Declaration: void srand(unsigned seed); Remarks: The random number generator is reinitialized by calling srand with an argument value of 1. The generator can be set to a new starting point by calling srand with a given seed number. Return Value: None Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: rand random randomize Example: #include <stdlib.h> #include <stdio.h> #include <time.h> int main(void) { int i; time_t t; srand((unsigned) time(&t)); printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; }
==================== strtod, _strtold, strtol, strtoul <STDLIB.H> ==================== * strtod converts a string to a double floating point * strtol converts a string to a long * _strtold converts a string to a long double * strtoul converts a string to an unsigned long Declaration: * double strtod(const char *s, char **endptr); * long strtol(const char *s, char **endptr, int radix); * long double _strtold(const char *(s), char **(endptr)); * unsigned long strtoul(const char *s, char **endptr, int radix); Remarks: * strtod converts character string s to a double value. * strtol converts character string s to a long integer value. * _strtold converts character string s to a long double value. * strtoul converts character string s to an unsigned long value. s is a sequence of characters that (depending on which function it is passed to) can be interpreted as one of the following * a double value (strtod) * a long value (strtol) * a long double value (_strtold) * an unsigned long value (strtoul) The characters in s must match this generic format: * strtod: [ws] [sn] [ddd] [.] [ddd] [fmt[sn]ddd] * strtol: [ws] [sn] [0] [x] [ddd] * _strtold: [ws] [sn] [ddd] [.] [ddd] [fmt[sn]ddd] * strtoul: [ws] [sn] [0] [x] [ddd] where * [ws] = optional whitespace * [sn] = optional sign (+ or -) * [ddd] = optional digits * [fmt] = optional e or E * [.] = optional decimal point * [0] = optional zero (0) * [x] = optional x or X strtod also recognizes +INF and -INF for plus and minus infinity, and +NAN and -NAN for Not-A-Number. These functions stop reading the string at the first character they don't recognize. Return Value: * On success, * strtol returns the value of s as a long * strtod returns the value of s as a double * _strtold returns the value of s as a long double * strtoul returns the value of s as an unsigned long * On error, * (in case of overflow) strtod returns plus or minus HUGE_VAL * (in case of overflow) _strtold returns plus or minus _LHUGE_VAL * strtol and strtoul return 0 Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + strtod | Yes | Yes | Yes | Yes | | _strtold | Yes | | Yes | | | strtol | Yes | | Yes | Yes | | strtoul | Yes | | Yes | Yes | | +-----+------+---------+--------+----------+ See Also: endptr argument radix argument atof atol Examples: strtod example strtol example strtoul example
endptr argument ================= (strtod, strtol, _strtold, and strtoul) If endptr is not null, these functions set *endptr (the "next character pointer") to point to the character that stopped the scan (*endptr = &stopper). endptr is useful for error detection.
radix argument to strtol and strtoul ====================================== strtol and strtoul use the argument radix (strtod does not). radix | How strtol and strtoul interpret it -------+------------------------------------ < 0 | Invalid value 0 | The first few characters of s | determine the base of the value | being converted: | 1st | 2nd | String s | char | char | interpreted as | ------+------+------------------- | 0 | 1-7 | Octal | 0 |x or X| Hexadecimal | 1-9 | | Decimal 1 | Invalid value 2--36 | Integer is expressed in base radix > 36 | Invalid value Any invalid value for radix causes the result to be 0 and sets *endptr to the starting string pointer. When s is interpreted as octal, any character other than 0 to 7 will not be recognized. When s is interpreted as decimal, any character other than 0 to 9 will not be recognized. When s is interpreted as a number in any other base (2--36), only the numerals and letters used to represent numbers in that base will be recognized. For example: radix | Recognized numerals and characters --------+------------------------------------ 5 | 0--4 20 | 0--9 and A--J
strtod example ================ #include <stdio.h> #include <stdlib.h> int main(void) { char input[80], *endptr; double value; printf("Enter a floating point number:"); gets(input); value = strtod(input, &endptr); printf("The string is %s the number is %lf\n", input, value); return 0; }
strtol example ================ #include <stdlib.h> #include <stdio.h> int main(void) { char *string = "87654321", *endptr; long lnumber; /* strtol converts string to long integer */ lnumber = strtol(string, &endptr, 10); printf("string = %s long = %ld\n", string, lnumber); return 0; }
strtoul example ================= #include <stdlib.h> #include <stdio.h> int main(void) { char *string = "87654321", *endptr; unsigned long lnumber; lnumber = strtoul(string, &endptr, 10); printf("string = %s long = %lu\n", string, lnumber); return 0; }
====== swab <STDLIB.H> ====== Swaps bytes Declaration: void swab(char *from, char *to, int nbytes); Remarks: swab copies nbytes bytes from the "from" string to the "to" string. nbytes should be even. Adjacent even- and odd-byte positions are swapped. This is useful for moving data from one machine to another machine with a different byte order. Return Value: None Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | | | +-----+------+---------+--------+----------+ Example: #include <stdlib.h> #include <stdio.h> #include <string.h> char source[15] = "rFna koBlrna d"; char target[15]; int main(void) { swab(source, target, strlen(source)); printf("This is target: %s\n", target); return 0; }
===================== wcstombs and wctomb <STDLIB.H> ===================== * wcstombs converts a wchar_t array into a multibyte string * wctomb converts wchar_t code to a multibyte character Declaration: * size_t wcstombs(char *s, const wchar_t *pwcs, size_t n); * int wctomb(char *s, wchar_t wc); Remarks * wcstombs converts the type wchar_t elements contained in pwcs into a multibyte character string s. The process terminates if wcstombs encounters either a null character or an invalid multibyte character. No more than n bytes are modified. If n bytes are processed before a null character is reached, the array s will not be null terminated. * wctomb: If s is not null, wctomb determines the number of bytes needed to represent the multibyte character corresponding to wc (including any change in shift state). The multibyte character is stored in s. At most MB_CUR_MAX characters are stored. If wc == 0, wctomb is left in the initial state. * NOTE: The LC_CTYPE setting of the current locale affects the behavior of both wcstombs and wctomb. Portability: + DOS + UNIX + Windows + ANSI C + C++ only + | yes | yes | yes | yes | | +-----+------+---------+--------+----------+ Return Value: * wcstombs: * If wcstombs encounters an invalid multibyte character, it returns (size_t - 1). * Otherwise, it returns the number of bytes modified, not including the terminating code, if any. * wctomb: * When wc points to an invalid multibyte character, wctomb returns -1. * When wc points to a valid multibyte character, wctomb returns the number of bytes contained in that multibyte character. * When wc points to the NULL character, * wctomb returns 0 if multibyte characters do not have state-dependent encodings. * wctomb returns non-zero if multibyte characters have state-dependent encodings. The wctomb return value will never exceed MB_CUR_MAX. See Also: mblen mbstowcs mbtowc setlocale
*fcmp: User-defined comparison routine for bsearch, lfind, lsearch, and qsort ======================================== To search the table, these functions make repeated calls to the comparison routine whose address is passed in fcmp. On each call to the comparison routine, these functions pass two arguments: Arg. | What It Points To ------+---------------------------------------------- key | The item being searched for (the search key) elem | The element of the table that the search key | is being compared to The comparison routine compares *key and *elem, and returns an integer based on the results of the comparison. For lsearch, *fcmp is free to interpret the search key and the table entries in any way. Return Value: *fcmp returns an integer based on the results of the comparison: *fcmp Return Value | bsearch | lfind | lsearch | qsort | Result of Comparison ---------+----------+----------+---------+---------------------- int < 0 | --- | --- | int < 0 | *key < *elem 0 | 0 | 0 | 0 | *key == *elem --- | int != 0 | int != 0 | --- | *key != *elem int > 0 | --- | --- | int > 0 | *key > *elem NOTE: This | Means the left element appears ------+--------------------------------------- < | Before the right element in the table (*) > | After the right element in the table (*) (*) For qsort, the left element appears before or after the right element in the final sorted sequence.
EDOM, ERANGE, HUGE_VAL <ERRNO.H, MATH.H> ======================== Name | Meaning ----------+------------------------------------ EDOM | Error code for math domain error ERANGE | Error code for result out of range HUGE_VAL | Overflow value for math functions
errno <ERRNO.H, STDDEF.H, STDLIB.H> ======= Variable indicating type of error Declaration: extern int errno; Whenever an error in a system call occurs, errno is set to a value indicating the type of error. See Also: _doserrno perror sys_errlist List of all global variables
Error numbers in errno <ERRNO.H> ======================== These are the mnemonics and meanings for the error numbers found in errno. Each value listed can be used to index into the sys_errlist array for displaying messages. Also, perror will display messages. Mnemonic | Meaning ----------+---------------------------------- EZERO | Error 0 EINVFNC | Invalid function number ENOFILE | File not found ENOPATH | Path not found ECONTR | Memory blocks destroyed EINVMEM | Invalid memory block address EINVENV | Invalid environment EINVFMT | Invalid format EINVACC | Invalid access code EINVDAT | Invalid data EINVDRV | Invalid drive specified ECURDIR | Attempt to remove CurDir ENOTSAM | Not same device ENMFILE | No more files ENOENT | No such file or directory EMFILE | Too many open files EACCES | Permission denied EBADF | Bad file number ENOMEM | Not enough memory ENODEV | No such device EINVAL | Invalid argument E2BIG | Arg list too long ENOEXEC | Exec format error EXDEV | Cross-device link EDOM | Math argument ERANGE | Result too large EFAULT | Unknown error EEXIST | File already exists
===================== _sys_nerr (#define) ===================== Highest defined system error number. Defined in errno.h See Also errno sys_errlist sys_nerr
lconv ======= Used by localeconv. struct lconv { char *decimal_point; char *thousands_sep; char *grouping; char *int_curr_symbol; char *currency_symbol; char *mon_decimal_point; char *mon_thousands_sep; char *mon_grouping; char *positive_sign; char *negative_sign; char int_frac_digits; char frac_digits; char p_cs_precedes; char p_sep_by_space; char n_cs_precedes; char n_sep_by_space; char p_sign_posn; char n_sign_posn; };
======================= localeconv, setlocale <LOCALE.H> ======================= * localeconv returns a pointer to the current locale structure * setlocale selects a locale Declaration: * struct lconv *localeconv(void); * char *setlocale(int category, char *locale); Remarks: * localeconv sets up country-specific numeric formats (monetary, time, etc.). * setlocale selects a locale. However, because Borland C++ currently only supports locale "C", invoking setlocale has no effect. Possible values for the locale argument of setlocale: * LC_ALL * LC_COLLATE * LC_CTYPE * LC_MONETARY * LC_NUMERIC * LC_TIME Return Value: * On success, * localeconv returns a pointer to the current locale structure * setlocale returns a string to indicate the locale that was in effect prior to invoking the function * On error, setlocale returns a NULL pointer Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | | Yes | Yes | | +-----+------+---------+--------+----------+ Examples: localeconv example setlocale example
localeconv example ==================== #include <locale.h> #include <stdio.h> int main(void) { struct lconv ll; struct lconv *conv = ≪ /* read the locality conversion structure */ conv = localeconv(); /* display the structure */ printf("Decimal Point : %s\n", conv->decimal_point); printf("Thousands Separator : %s\n", conv->thousands_sep); printf("Grouping : %s\n", conv->grouping); printf("International Currency symbol : %s\n", conv->int_curr_symbol); printf("$ thousands separator : %s\n", conv->mon_thousands_sep); printf("$ grouping : %s\n", conv->mon_grouping); printf("Positive sign : %s\n", conv->positive_sign); printf("Negative sign : %s\n", conv->negative_sign); printf("International fraction digits : %d\n", conv->int_frac_digits); printf("Fraction digits : %d\n", conv->frac_digits); printf("Positive $ symbol precedes : %d\n", conv->p_cs_precedes); printf("Positive sign space separation : %d\n", conv->p_sep_by_space); printf("Negative $ symbol precedes : %d\n", conv->n_cs_precedes); printf("Negative sign space separation : %d\n", conv->n_sep_by_space); printf("Positive sign position : %d\n", conv->p_sign_posn); printf("Negative sign position : %d\n", conv->n_sign_posn); return 0; }
setlocale example =================== #include <locale.h> #include <stdio.h> int main(void) { char *old_locale; /* The only locale supported in Turbo C++ is "C" */ old_locale = setlocale(LC_ALL,"C"); printf("Old locale was %s\n",old_locale); return 0; }
=========== VARARGS.H =========== Definitions for accessing parameters in functions that accept a variable number of arguments. These macros are compatible with UNIX System V. Use STDARG.H for ANSI C compatibility. NOTE: You can't include both STDARG.H and VARARGS.H Macros ====== va_start va_arg va_end Type ==== va_list
========================== va_arg, va_end, va_start <STDARG.H> ========================== Macros that implement variable argument lists Declaration: * void va_start(va_list ap, lastfix); * type va_arg(va_list ap, type); * void va_end(va_list ap); Remarks: Some C functions, such as vfprintf and vprintf, take variable argument lists in addition to taking a number of fixed (known) parameters. The va_arg, va_end, and va_start macros provide a portable way to access these argument lists. * va_start sets ap to point to the first of the variable arguments being passed to the function. * va_arg expands to an expression that has the same type and value as the next argument being passed (one of the variable arguments). Because of default promotions, you can't use char, unsigned char, or float types with va_arg. * va_end helps the called function perform a normal return. Argument | What It Is/Does ----------+-------------------------------------------------------------- ap | Points to the va_list variable argument list being passed to | the function. | The ap to va_arg should be the same ap that va_start | initialized. | NOTE: va_end might modify ap in such a way that it can't be | used unless va_start is recalled. | lastfix | The name of the last fixed parameter being passed to the | called function. type | Used by va_arg to perform the dereference and to locate the | following item. You use these macros to step through a list of arguments when the called function does not know the number and types of the arguments being passed. Calling Order ============= va_start must be used before the first call to va_arg or va_end. va_end should be called after va_arg has read all the arguments. Failure to do so might cause strange, undefined behavior in your program. Stepping Through the Argument List ================================== The first time va_arg is used, it returns the first argument in the list. Each successive time va_arg is used, it returns the next argument in the list. It does this by first dereferencing ap, then incrementing ap to point to the next item. Return Value: va_start and va_end return no values. va_arg returns the current argument in the list (the one that ap is pointing to). Portability: + DOS + UNIX + Windows + ANSI C + C++ Only + | Yes | Yes | Yes | Yes | | +-----+------+---------+--------+----------+ Example: #include <stdio.h> #include <stdarg.h> /* calculate sum of a 0 terminated list */ void sum(char *msg, ...) { int total = 0; va_list ap; int arg; va_start(ap, msg); while ((arg = va_arg(ap,int)) != 0) { total += arg; } printf(msg, total); va_end(ap); } int main(void) { sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0); return 0; }
========= va_list <STDARG.H> ========= Array that holds information needed by va_arg and va_end When a called function takes a variable argument list, it declares a variable ap of type va_list.
NULL ====== Null pointer value. Defined in: ALLOC.H MEM.H STDDEF.H STDIO.H STDLIB.H
wchar_t <STDDEF.H, STDLIB.H> ========= Wide-character constant (C only) A character constant preceded by an L is a wide-character constant.
MAXxxxx <VALUES.H> ========= Maximum values for integer data types Name | Meaning ----------+------------------ MAXSHORT | Largest short MAXINT | Largest int MAXLONG | Largest long
BITSPERBYTE <VALUES.H> ============= Number of bits in a byte.
Float and Double Limits <VALUES.H> ========================= ----------------------------------------------- UNIX System V compatible: --------------+-------------------------------- _LENBASE | Base to which exponent applies --------------+-------------------------------- Limits for double float values --------------+-------------------------------- _DEXPLEN | Number of bits in exponent DMAXEXP | Maximum exponent allowed DMAXPOWTWO | Largest power of two allowed DMINEXP | Minimum exponent allowed DSIGNIF | Number of significant bits MAXDOUBLE | Largest magnitude double value MINDOUBLE | Smallest magnitude double value --------------+-------------------------------- Limits for float values --------------+-------------------------------- _FEXPLEN | Number of bits in exponent FMAXEXP | Maximum exponent allowed FMAXPOWTWO | Largest power of two allowed FMINEXP | Minimum exponent allowed FSIGNIF | Number of significant bits MAXFLOAT | Largest magnitude float value MINFLOAT | Smallest magnitude float value
HIBITx <VALUES.H> ======== Bit mask for the high (sign) bit of standard integer types. Name | Meaning --------+------------------ HIBITS | For type short HIBITI | For type int HIBITL | For type long