digitalmars.com                      
Last update Sat Jun 18 16:54:33 2011

stdlib.h

Note: long long forms are not supported by 16 bit memory models. Wide character forms are only in Win32.

__max

Header
stdlib.h
Prototype
__max(a, b);
Description
The __max function compares the values a and b and then returns the larger one. The arguments can be of any numeric data type. The arguments and return value must be the same data types.
Synonym
Function: max
Return Value
The larger value in arguments a or b.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
__min
Example
/* Example of __max */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 int x = 5, y = 6, z, w;

 z = __max(x, y);
 w = __min(x, y);

 printf("The max should be 6 and is %d\n",
        z);
 printf("The min should be 5 and is %d\n",
        w);
}
Output
The max should be 6 and is 6
The min should be 5 and is 5

__min

Header
stdlib.h
Prototype
__min(a, b);
Description
The __min function compares two values and returns the smaller one. The arguments can be of any numeric data type. The a and b arguments and the return value must all be of the same data type.
Synonym
Function: min
Return Value
The smaller of the two arguments.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
__max
Example
See __max

_alloca

Header
stdlib.h
Prototype
void *_alloca(size_t size);
Description
The _alloca function allocates a number of bytes (specified in the size parameter) on the program's stack. The allocated space is automatically freed when the calling function exits. Restrictions are:

  • Do not use the _alloca function in an expression that is an argument to a function.
  • Any function that references _alloca must declare at least one local variable. When you compile with optimization on, the stack pointer might not be restored properly in functions that have no local variables and that reference _alloca. (This restriction does not apply to programs compiled with the DOSX memory model.)
  • Do not pass the pointer value returned by _alloca as an argument to free.
Synonym
Function: alloca
Return Value
A pointer to the allocated stack area. If space cannot be allocated, the return value is NULL.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
calloc Functions malloc Functions realloc Functions _stackavail
Example
/* Example for _alloca, _stackavail */
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

void main() {
 char *buffer;

 printf("Stack available before
         _alloca:%u\n",
         _stackavail());
 buffer = _alloca(100* sizeof(char));
 printf("Stack available after
          _alloca:%u\n",
          _stackavail());
}
Output
Output will be similar to:
Stack available before _alloca: 4804
Stack available after _alloca: 4694

_atold

Header
stdlib.h
math.h
Prototype
long double _atold(const char *nptr);
Description
Converts the string pointed to by nptr into a long double. The input string is a sequence of characters that can be interpreted as a numerical value of the specified type. The string may have leading spaces, tabs, and + or -. It represent a decminal point number. This number can be followed by an exponent that has an introductory letter (d, D, e, or E) and an optionally signed decimal integer.

Conversion stops on the first unrecognized character. If there are no recognized characters, the result is 0. 0 (for _atold).

Return Value
Returns the long double value derived from converting the string. Zero is returned if the string has no recognizable characters.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
atof atoi atol _ecvt _fcvt scanf strtol

_chkstack

Header
dos.h
Prototype
size_t _chkstack(void);
Description
_chkstack determines if the stack has grown larger than the memory allocated for it and if so, aborts the program with a stack overflow message. This function should be called in recursive functions or other functions that might use a lot of stack space. Alternatively, stack checking can be inserted in the code automatically at compilation both from within the environment and by using the -s switch in the command line. In the 32-bit memory models, the 80386 segment protection mechanism automatically aborts the program if stack space grows into the heap so this function is not implemented.
Return Value
Returns the number of bytes remaining on the stack, if the stack has not overflowed.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
Example
To compile the following example as a C++ program, declare _stack as extern "C" because _stack has C linkage. For example:
extern "C" unsigned _stack = 2048
The example:
/* Example for _chkstack */

#include <dos.h>
#include <stdio.h>

/* Sets stack size */
unsigned _stack = 2048;

void crush_stack(void)
{
 static int count = 0;
 int remaining_stack;
 char a_chunk_of_memory[128];

 *a_chunk_of_memory = '\0';
 remaining_stack = _chkstack();
 count += 1;
 printf("On call number %d, stack size =
         %d\n", count, remaining_stack);
 crush_stack();
}

void main()
{
  crush_stack();
}
Output
On call number 1, stack size = 1876
On call number 2, stack size = 1742
On call number 3, stack size = 1608
On call number 4, stack size = 1474
On call number 5, stack size = 1340
On call number 6, stack size = 1206
On call number 7, stack size = 1072
On call number 8, stack size = 938
On call number 9, stack size = 804
On call number 10, stack size = 670
On call number 11, stack size = 536
On call number 12, stack size = 402
On call number 13, stack size = 268
Stack Overflow

_cpumode

Header
stdlib.h
Prototype
extern unsigned char _cpumode;
Description
This variable specifies the mode in which the processor is running. It can have one of the following values:
_REAL_MODE Real mode
_PROT_MODE Protected mode
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_ecvt

Header
stdlib.h
Prototype
char *_ecvt(double val, int ndig, int *decpt, int *sign)
Description
_ecvt converts a double value to a string of digits. The val argument is the value to be converted and the ndig argument specifies the number of digits of val to be converted. If ndig is less than the actual number of digits in val, the digit string is rounded. If val has fewer than ndig digits, the string is padded with 0's.

The decpt argument points to an integer that specifies the location of the decimal point, relative to the the first digit in the string. If the integer is negative, the decimal point is positioned the specified number of places to the left of the first digit.

The sign argument points to an integer that indicates the sign of the converted string. If the integer is 0, the string specifies a positive number. Otherwise, the string specifies a negative number.

The converted string is written into a statically allocated area, which is also used by the fcvt and printf function. Therefore, a call to one of these functions overwrites the result of the previous call.

Synonym
Function: ecvt
Return Value
A pointer to the string of digits. Otherwise, returns no error.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_fcvt sprintf
Example
/* Example for _ecvt */
#include <stdio.h>
#include <stdlib.h>

void main() {
 double test;
 char *result;
 int decimalpt, sign;

 printf("Enter a number: ") ;
 scanf("%lf", &test);

 printf("\nInput was %g\n", test);

 result = _ecvt(test,5,&decimalpt,&sign);
 printf("Result string is '%s'\n",
        result);
 printf("where the number of digits is
         5, the decimal point is ");
 printf("at position %d,\nand the sign
         value is %d\n",
         decimalpt, sign);
}
Output
Enter a number: -21.433
Input was -21.433
Result string is '21433'
where the number of digits is 5, the decimal
point is at position 2,
and the sign value is 1

_environ

Header
stdlib.h
Prototype
extern char **_environ;
Description
This variable points to an array of pointers, which point to zero or more environment variable strings for the process. The value of each string in the form, NAME=string. The string can be empty.

When a program executes, its initial environment variable settings are copied from the environment of the parent program, which is usually the operating system. Functions getenv and _putenv use _environ to search for and modify the settings. Using _putenv to add or delete settings changes the size of the environment table, and can also change the table's memory location, depending on memory requirements of the program. In these cases, _environ adjusts and points to the correct table location.

Synonym
Variable: environ
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_exit

Header
process.h
stdlib.h
Prototype
void _exit(int exitstatus);
Description
_exit closes all output files and returns to the operating system with an exit status given by exitstatus. It does not call the static destructors or flush the buffers, but immediately returns to the operating system. exit is preferred over _exit for C++ programs. exitstatus is normally EXIT_SUCCESS to indicate a normal end of program and EXIT_FAILURE to indicate an error. Only the lower order byte of exitstatus is returned to the parent process. The exit status can be referenced by the name ERRORLEVEL in batch files and as the return value from calls to spawn functions.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
abort exit _spawn Functions
Example
/* Example for _exit, exit */

#include <process.h>
#include <stdio.h>
#include <stdlib.h>

void main()
{
 int input = 0;
 printf("Program demonstrating different
         paths out of a program\n");

 while (input <1|| input >2)
 {
   printf("\nSelect :\n1 to call exit(),
           \n2 to call _exit()\n");
   scanf("%d", &input);
 }
 if (input == 1)
 {
   printf("Calling exit(). Files will be
           closed, buffers flushed,
	   and\n");
   printf("static destructors called.\n");
   exit(EXIT_SUCCESS);
 }
 else
 {
   printf("Calling _exit(). Files will be
           closed, buffers will not be \n");
   printf("flushed and static destructors
           will not be called.\n");
   _exit(EXIT_SUCCESS);
 }
}
Output
Program demonstrating different paths out of a program

Select :
1 to call exit(),
2 to call _exit() 1
Calling exit(). Files will be closed, buffers flushed, and
static destructors will not becalled.
or
Program demonstrating different paths out of a program

Select :
1 to call exit(),
2 to call _exit()
2
Calling _exit(). Files will be closed, buffers will not be
flushed and static destructors will not be called.

_fcvt

Header
stdlib.h (for _fcvt)
Prototype
char *_fcvt(double val, int count, int *decpt, int *sign);
Description
_fcvt converts a floating-point value to a string of digits. The val argument is the value to be converted, the count argument specifies the number of digits (of val) to be stored after the decimal point. If count is less than the actual number of digits to the right of the decimal point in val, the digit string is rounded. If val has fewer than count digits of precision, the string is padded with 0's.

The decpt argument points to an integer that specifies the location of the decimal point, relative to the the first digit in the string. If the integer is negative, the decimal point is positioned the specified number of places to the left of the first digit.

The sign argument points to an integer that indicates the sign of the converted string. If the integer is 0, the string specifies a positive number. Otherwise, the string specifies a negative number.

The converted string is written into a statically allocated area, which is also used by the ecvt and printf functions. Therefore, a call to one of these functions overwrites the result of the previous call.

Synonym
Function: fcvt
Return Value
A pointer to the string of digits. No return value for an error.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_ecvt sprintf
Example
/* Example for fcvt */

#include <process.h>
#include <stdio.h>
#include <stdlib.h>

void main()
{
 double test;
 char *result;
 int decimalpt, sign;

 printf("Enter a number: ") ;
 scanf("%lf", &test);

 printf("\nInput was %g\n", test);

 result = fcvt(test,5,&decimalpt,&sign);
 printf("Result string is '%s'\n",
        result);
 printf("where the number of digits
         after the
         decimal point is 5,\n");
 printf("the decimal point is at
         position %d,", decimalpt);
 printf("\nand the sign value is %d\n",
         sign);
}

_fileinfo

Header
stdlib.h
Prototype
extern int _fileinfo;
Description
_fileinfo controls the passing of file information to a child process. By default, _fileinfo is set to 0 and does not pass information to the child.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

mblen

Header
stdlib.h
Prototype
int mblen(const char *s, size_t n);
int __far _fmblen(const char __far *s, size_t n);
Description
mblen returns the number of bytes in the multi-byte character that s points to. n is the maximum number of bytes to check in the character.

_fmblen is a model-independent (large-model) form of the mblen function.

Return Value
If s is not null, both functions return the number of bytes in the multi-byte character s. If s is null, or if the string that it points to does not contain a multi-byte character in the first n characters, both functions return -1.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbstowcs mbtowc wcstombs wctomb

mbstowcs

Header
stdlib.h
Prototype
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n);
size_t __far _fmbstowcs(wchar_t __far *pwcs, const char __far *s, size_t n);
Description
mbstowcs converts n or fewer multi-byte characters, from the s string, to a sequence of wide character codes. The resulting wide character string is stored in the array pcws. The wide character string in pcws is not null-terminated, unless a null character is encountered during conversion. If the s string contains a null character before n bytes, the null character is converted to a wide-character null character (L'\0').

_fmbstowcs is a model-independent (large-model) form of the mbstowcs function.

Return Value
The number of converted multi-byte characters. If either function encounters an invalid multi-byte character, it returns -1.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbtowc wcstombs wctomb
Example
See wcstombs

mbtowc

Header
stdlib.h
Prototype
int mbtowc(wchar_t *pwc, const char *s, size_t n);
int __far _fmbtowc(wchar_t __far *pwc, const char *s, size_t n);
Description
mbtowc converts the multi-byte character s to a corresponding wide character code (converting no more than n bytes), stores the code in the object pwc points to, and returns the length in bytes of the multi-byte character.

_fmbtowc is a model-independent (large-model) form of the mbtowc function.

Return Value
Both functions return the number of bytes copied, if successful. If s points to an invalid character, -1 is returned. If s is null, both functions return 0.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbtowc wcstombs wctomb

_fmode

Header
stdlib.h
Prototype
extern int __cdecl _fmode;
Description
This variable controls the default file translation mode. Modes are:
_O_TEXT Text mode. Carriage return/line feeds are converted to line feeds. This is the default.
_O_BINARY Binary mode. No conversions take place.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_onexit

Header
stdlib.h
Prototype
_onexit_t _onexit(_onexit_t func);
_fonexit_t __far _fonexit(_fonexit_t func);
Description
_onexit specifies a function to be called when a program terminates normally. Successive calls to _onexit create a register of functions that are executed in LIFO order. No more than 32 functions can be registered with _onexit; NULL is returned if the number exceeds 32. For 32-bit platforms, 64 functions can be registered. The functions passed to _onexit do not take parameters.

The _fonexit function is a far version of _onexit; it can be used with any memory model.

Neither _onexit nor _fonexit are part of the ANSI definition. Use the atexit function for ANSI portability.

Synonym
Function: onexit
Return Value
If successful, both functions return a pointer to the function. NULL is returned if there is no space left to store the function pointer.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
atexit exit
Example
/* Example of _onexit */

#include <stdio.h>
#include <stdlib.h>

void func1()
{
 printf("LAST printf\n");
}

void func2()
{
 printf("This is the ");
}

void main()
{
 _onexit((_onexit_t) func1);
 _onexit((_onexit_t) func2);
 printf("This is the FIRST printf\n");
}
Output
This is the FIRST printf
This is the LAST printf

_freect

Header
malloc.h
Prototype
unsigned int _freect(size_t size);
Description
The _freect function determines the number of times a program can call a malloc function to allocate size bytes from the near heap. The _freect function determines this value by dividing the amount of memory that is available for dynamic memory allocation (in the default data segment) by the size argument.
Return Value
The number of times a program can call a malloc function to allocate size bytes from the near heap.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
malloc Functions
Example
/* Example for _freect */

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

void main()
{
 int i;
 printf("There is memory available
         for %u integers\n",
        _freect(sizeof(int)));

 for (i = 0; i < 1000; i++)
    malloc(sizeof(int));

 printf("After allocating 1000
         integers there
         is room for %u more\n",
         _freect(sizeof(int)));
}
Output
There is memory available for 15502 integers
After allocating 1000 integers there is room for
14374 more

_fullpath

Header
stdlib.h
Prototype
char *_fullpath(char *buffer, const char *pathname, size_t maxlen);
Description
The _fullpath function converts the relative pathname in the pathname argument to an absolute (fully qualified) pathname. The converted pathname is stored in the buffer argument. Argument maxlen specifies the length of the buffer buffer. If the length of the converted pathname is greater then maxlen, NULL is returned.

If the buffer argument is NULL, the _fullpath function allocates a buffer of _MAX_PATH size using malloc, and the maxlen argument is ignored. The caller must deallocate this buffer (using free) when appropriate.

If the pathname argument specifies a disk drive, the current directory of this drive is combined with the path. If the drive is not valid, _fullpath returns NULL.

Synonym
Function: fullpath
Return Value
Returns a pointer to the buffer containing the converted pathname. Returns NULL if an error occurs.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_getcwd
Example
/* Example for _fullpath */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 char fname[_MAX_PATH];
 char full[_MAX_PATH];

 printf("Enter a filename: ");
 gets(fname);

 if (_fullpath(full,fname,_MAX_PATH) == NULL)
 {
    perror("Error calling fullpath()");
    exit(EXIT_FAILURE);
 }
 printf("The full path name is \"%s\"\n",
         full);
}
Output
Enter a filename: _fullpat.c
The full path name is "c:\dm\examples\_fullpat.c"

wcstombs

Header
stdlib.h
Prototype
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n);
size_t __far _fwcstombs(char __far char *s, const wchar_t __far *pwcs, size_t n);
Description
wcstombs converts the sequence of wide character codes pwcs to
a multi-byte character string, stores it in the array s points to, and returns the number of array elements changed.

_fwcstombs is a model-independent (large-model) form of the wcstombs function.

Return Value
The number of wide characters copied.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mblen mbstowcs mbtowc wctomb

wctomb

Header
stdlib.h
Prototype
int wctomb(char *s, wchar_t wchar);
int __far _fwctomb(char __far *s, wchar_t wchar);
Description
wctomb converts wchar to a multi-byte character, stores it in the array s points to, and returns the length in bytes of the wide character.

_fwctomb is a model-independent (large-model) form of the wctomb function.

Return Value
If successful, both functions return the number of bytes copied. If conversion is not possible, -1 is returned. If wchar is the wide-character null character, 0 is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
wcstombs mbstowcs mbtowc

_gcvt

Header
stdlib.h
Prototype
char *_gcvt(double value, int digits, char *buffer);
Description
The _gcvt function converts the floating-point value in the value argument to a character string. The digits argument defines the number of significant digits. The resulting string is stored in the location pointed to by the buffer argument. A terminating null character is automatically appended.

The _gcvt function attempts to represent significant digits in decimal format. If not possible, the function represents significant digits in exponential format. Trailing zeros might be suppressed.

Be sure that buffer is large enough to accomodate the converted value, which may include a decimal point, a sign, exponent information, and the terminating null character.

Synonym
Function: gcvt
Return Value
A pointer to the string of digits. There is no error return.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_ecvt _fcvt
Example
/* Example for _gcvt */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 char buffer[25];
 int precision = 4;
 double source = 3.1415926535;

 _gcvt(source, precision, buffer);
 printf("The number %8.16f converted to
         the string \"%s\"\n",
         source, buffer);
}
Output
The number 3.1415926535000000 converted to the
string "3.142"

_halloc

Header
stdlib.h
Prototype
void __huge *_halloc(long num, size_t size);
Description
The _halloc function allocates a huge array. The array consists of a number of elements, num; each element's size is represented as size. Each element is initialized to 0. If the size of the array is greater than 128K (131, 072 bytes), the size of each element must be a power of 2.

To free memory allocated by _halloc, use _hfree.

Return Value
A void huge pointer to the allocated space; NULL if unsuccessful.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
free Functions _hfree malloc Functions
Example
/* Example for _halloc,
   _hfree, _filelength, _read

   This program must be compiled with the
   large or compact memory models, which
   allow _read to read into __far
   buffers.
*/

#include <malloc.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>

static void error(char *message)
{
 perror(message);
 exit(EXIT_FAILURE);
}

void main()
{
 char __huge *buffer;
 char filename[FILENAME_MAX];
 char __huge *chunk;
 char __huge *byte;
 int handle;
 long size;
 unsigned actual;

 fprintf(stderr,
         "Enter name of file to
          reverse: ");
 gets(filename);
 handle = _open(filename, _O_RDONLY |
          _O_BINARY);
 if (handle == -1)
    error(" Couldn't open file");
 size = _filelength(handle);
 if (size == -1)
    error(" Couldn't access file size");
 buffer = _halloc(size, sizeof(char));
 if (buffer == NULL)
 {
    printf("Couldn't get a huge block %ld
            bytes long\n", size);
    exit(EXIT_FAILURE);
 }
 for(chunk = buffer;
     chunk < buffer + size;
     chunk += actual)
 {
    actual = _read(handle,
		(void *)chunk,
                0xfffe);
    if (actual == 0)
       break;
 }
 for (byte = chunk - 1;
      byte > buffer;
      byte -= 1)
    putchar(*byte);
    _hfree(buffer);
}
Output
c:\dm\examples>_halloc
Enter name of file to reverse: _halloc.c
}

;) reffub(eerfh_

;) etyb*(rahctup

)1 =-etyb ;reffub > etyb ;1 -knuhc = etyb(rof

}

;kaerb

)0 == lautca(fi

;)" daer no rorrE"(rorre

)1-== lautca(fi

;) efffx0 ,knuhc)* diov(,eldnah(daer_= lautca
.
.

_hfree

Header
stdlib.h
Prototype
void _hfree(void __huge *memblock);
Description
The _hfree function deallocates a huge memory block. Argument memblock points to the memory previously allocated by _halloc.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
free Functions _halloc

_itoa

Header
stdlib.h
Prototype
char *_itoa(int value, char *str, int radix);
Description
The _itoa function converts the value (in the value argument) to a null terminated string using the radix (base) specified in the radix argument. The radix must be in the range between 2 and 36. If value is negative and the radix is 10, the first character of the stored string is '-'. The result is stored in the string pointed to by str, which must be large enough to hold the result.
Synonym
Function: itoa
Return Value
Returns str. Errors are not returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_ltoa
Example
/* Example of _itoa */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 char buffer[10], *ptr;
 int value = 67;

 ptr = _itoa(value, buffer, 2);
 printf("The number %d in binary is
         \"%s\"\n",value,buffer);

 ptr = _itoa(value, buffer, 8);
 printf("The number %d in octal is
         \"%s\"\n",value,buffer);

 ptr = _itoa(value, buffer, 16);
 printf("The number %d in hex is
         \"%s\"\n",value,buffer);
}
Output
The number 67 in binary is "1000011"
The number 67 in octal is "103"
The number 67 in hex is "43"

_lrotl

Header
stdlib.h
Prototype
unsigned long _lrotl(unsigned long val, int shift);
unsigned long _lrotr(unsigned long val, int shift);
Description
The functions _lrotl and _lrotr carry out a binary rotation of the supplied unsigned long value, by shifting bits.
Return Value
The rotated value as an unsigned long. There is no error return.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_rotl _rotr
Example
/* Example of _lrotl, _lrotr */
#include <stdio.h>
#include <stdlib.h>

void main()
{
 unsigned long value = 0x01234567;
 printf("value = %016b\n\n", value);
 printf("left 2 = %016b\n",
        _lrotl(value,2));
 printf("left 4 = %016b\n",
        _lrotl(value,4));
 printf("left 6 = %016b\n",
        _lrotl(value,6));
 printf("left 8 = %016b\n\n",
        _lrotl(value,8));
 printf("right 2 = %016b\n",
        _lrotr(value,2));
 printf("right 4 = %016b\n",
        _lrotr(value,4));
 printf("right 6 = %016b\n",
        _lrotr(value,6));
 printf("right 8 = %016b\n",
        _lrotr(value,8));
}
Output
value = 0100010101100111

left 2 = 0001010110011100
left 4 = 0101011001110000
left 6 = 0101100111000000
left 8 = 0110011100000001

right 2 = 1101000101011001
right 4 = 0011010001010110
right 6 = 1000110100010101
right 8 = 0010001101000101

_ltoa

Header
stdlib.h
Prototype
char *_ltoa(long number, char *string, int radix);
Description
The _ltoa function converts the long integer number into a null terminated string using the base specified in radix. The radix must be in the range 2 through 36. Attempts to use any other base causes _ltoa to ignore the radix argument and convert to decimal. If radix equals 10 and value is negative, the first character of the converted string is a minus sign. All conversions for bases other than 10 are unsigned.
Return Value
A pointer to the converted string.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_itoa
Example
/* Example of _ltoa */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 char buffer[20], *ptr;
 long value = 6989L;

 ptr = _ltoa(value, buffer, 2);
 printf("The number %ld in binary is
        '\"%s\"\n", value, buffer);

 ptr = _ltoa(value, buffer, 8);
 printf("The number %ld in octal is
        '\"%s\"\n", value, buffer);

 ptr = _ltoa(value, buffer, 16);
 printf("The number %ld in hex is
        '\"%s\"\n", value, buffer);
}
Output
The number 6989 in binary is '" 1101101001101"
The number 6989 in octal is '" 15515"
The number 6989 in hex is '" 1b4d"

_makepath

Header
stdlib.h
Prototype
void _makepath(char *path, const char *drive, const char *dir, const char *fname, const char *ext);
Description
The _makepath function constructs a pathname from the drive, directory, filename, and file extension specified in the argument list. The constructed pathname is stored in the location pointed to by the path argument. Be sure path buffer is large enough to hold the constructed pathname; constant _MAX_PATH, defined in stdlib.h, defines the maximum pathname size.

Rules that apply to each component of the pathname are:

  • If argument drive specifies a letter (A, B, etc) without a trailing colon, _makepath automatically inserts the colon. If drive is a null character or an empty string, no drive letter or colon appears in the constructed pathname.
  • If argument dir specifies a name without a trailing backslash, _makepath automatically inserts the backslash. If dir is a null character or an empty string, no directory name or backslash appears in the constructed pathname.
  • If argument fname is a null character or an empty string, no filename appears in the constructed pathname.
  • If argument ext does not contain the leading period, the _makepath function automatically inserts it. If ext is a null character or an empty string, no extension name or period appears in the constructed pathname.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_fullpath _splitpath
Example
/* Example of _makepath */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>
#include <direct.h>

void main()
{
 char s[_MAX_PATH];
 char drive[_MAX_DRIVE];
 char dir[_MAX_DIR];
 char file[_MAX_FNAME];
 char ext[_MAX_EXT];

 _getcwd(s, _MAX_PATH);
 if (s[strlen(s) -1] != '\\')
     strcat(s, "\\");
 _splitpath(s, drive, dir, file, ext);
 strcpy(file, "DATA");
 strcpy(ext, ".EXT");
 _makepath(s, drive, dir, file, ext);
 puts(s);
}
Output
C:\SC\EXAMPLES\DATA.EXT

_memavl

Header
stdlib.h
Prototype
size_t _memavl(void);
Description
The _memavl function returns the approximate number of bytes of memory available for dynamic memory allocation from the near heap (default data segment). These bytes are not necessarily continguous. To find the largest number of contiguous bytes, use the _memmax function.
Return Value
The approximate number of bytes of memory available for dynamic memory allocation.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
calloc Functions _freect malloc Functions _memmax realloc Functions
Example
/* Example of _memavl */

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

void main()
{
 long *ptr;
 printf("Memory available %u\n", _memavl());
 ptr = _nmalloc(1000 * sizeof(long));
 if (ptr != NULL)
 {
   printf("Memory now available %u\n",
          _memavl());
   _nfree(ptr);
 }
}
Output
Memory available 59006
Memory now available 54490

_memmax

Header
stdlib.h
Prototype
size_t _memmax(void);
Description
The _memmax function returns the size in bytes of the largest contiguous block of memory that is available for allocation from the near heap (the default data segment).
Return Value
The block size is returned. If unsuccessful, 0 is returned, indicating that nothing more can be allocated from the near heap.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
malloc Functions _memavl _msize Functions
Example
/* Example of _memmax */

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

void main()
{
 long *ptr;
 printf("Largest contiguous block of
         memory is %u\n", _memmax());
 ptr = _nmalloc(1000 * sizeof(long));
 if (ptr == NULL)
 {
    printf("Now the largest block is %u\n",
    _memmax()); _nfree(ptr);
 }
}
Output
Largest contiguous block of memory is 58992
Now the largest block is 54476

_msize

Header
stdlib.h
Prototype
size_t _msize(void *memblock);
size_t _fmsize(void __far *memblock);
size_t _nmsize(void __near *memblock);
Description
The _msize functions return the size, in bytes, of the memory block allocated by a previous call to the appropriate version of the calloc, malloc, or realloc functions. For example, _fmsize returns the size of a memory block allocated by _fcalloc, _fmalloc, or _frealloc.

In large data models, _msize maps to _fmsize. In small data models, _msize maps to _nmsize.

Return Value
The size, in bytes, as an unsigned integer.
Compatibility
_msize: DOS, Windows 3. x, Phar Lap/ DOSX, Win32
_fmsize: DOS, Windows 3.x, Phar Lap/ DOSX, Win32
_nmsize: DOS, Windows 3. x, Phar Lap/ DOSX, Win32
See Also
calloc Functions malloc Functions realloc Functions
Example
/* Example of _msize */

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h&t

void main()
{
 long *buffer;
 size_t size;

 buffer = (long *)malloc(100 * sizeof(long));
 size = _msize(buffer);
 printf("The size of the buffer is %d\n",
        size);
}
Output
The size of the buffer is 400

_osmajor

Header
stdlib.h
Prototype
extern unsigned char _osmajor;
Description
This variable defines the major version number of the operating system. For example, its value running under MS-DOS 5. 0 is 5.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_osminor

Header
stdlib.h
Prototype
extern unsigned char _osminor;
Description
This variable defines the minor version number of the operating system. For example, its value running under MS-DOS 3.1 is 10.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_osmode

Header
stdlib.h
Prototype
extern unsigned char _osmode;
Description
This variable indicates which operating system is currently running:

_DOS_MODE is 0 and indicates DOS or Phar Lap
_WIN_MODE is 2 and indicates Windows 3. x or Win32.

Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_osver

Header
stdlib.h
Prototype
extern unsigned int _osver;
Description
For DOS, Windows 3. x, and Phar Lap, the _osver variable holds both the major and minor version numbers of the operating system. The high byte holds the major version number; the low byte holds the minor version number. This is the reverse of _osversion. For Win32 bit 15 is set to indicate the operating system platform: 0 is NT, 1 is Win32. The other bits are not significant.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_pgmptr

Header
stdlib.h
Prototype
extern char __far *_pgmptr;
Description
This variable is automatically initialized at startup to point to the full path of the executing program.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_psp

Header
stdlib.h
Prototype
extern unsigned _psp;
Description
This variable contains the segment paragraph address of the program segment prefix. Use _psp to construct a far pointer, allowing access to the program segment prefix from within the program.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_putenv

Header
stdlib.h
Prototype
int _putenv(const char *envstring);
Description
The _putenv function adds or modifies environment variables. The envstring has the form varname = string, where varname represents an environment variable name and string represents the new setting. If the environment variable already exists, it is assigned the new setting. Otherwise, the variable is added. To remove an environment variable, specify an empty string. (For example, varname =.)

The _putenv function affects the local environment for the current process; it does not modify the command-level environment. Any environment variable set will revert to its previous setting upon program termination. However, an environment variable set by _putenv is passed to spawned programs. The _putenv function complements the getenv function in the standard library. The library getenv function can be used to access environment variables set using putenv.

Functions getenv, _putenv, and putenv use global variable _environ to search for and modify the settings. Using _putenv to add or delete settings, changes the size of the environment table, and can also change the table's memory location, depending on memory requirements of the program. In these cases, _environ adjusts and points to the correct table location.

Return Value
Returns 0 if successful. Returns -1 if an error occurs.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
getenv
Example
/* Example of _putenv
 * dumpenv.exe must also be built.
 */

#include <stdio.h>
#include <stdlib.h>
#include <process.h>

void main()
{
 if (_putenv("ENVAR=New environment variable"))
 {
   perror("Could not set environment variable");
   exit(EXIT_FAILURE);
 }
 else
   _spawnlp(_P_WAIT,"dumpenv.exe",NULL);
}


/*
 * Example for _putenv
 * Compile program to file:
 *    dumpenv.exe
 */

#include <stdio.h>

void main(int argc, char *argv[],
          char* envp[])
{
 char **ep;

 ep = envp;
 while (*ep)
 {
    puts(*ep);
    ep++;
 }
}
Output
COMSPEC=C:\COMMAND.COM
PROMPT=$p$g
INCLUDE=c:\dm\include
LIB=c:\dm\lib
TEMP=c:\dos
PATH=c:\windows;c:\dm\bin;c:\dos;
ENVAR=New environment variable

_rotl

Header
stdlib.h
Prototype
unsigned int _rotl(unsigned int val, int shift);
unsigned int _rotr(unsigned int val, int shift);
Description
The functions _rotl and _rotr carry out a binary rotation of the supplied unsigned integer, val, by shift bits.
Return Value
Both of these functions return the rotated value as an unsigned int. Errors are not returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_lrotl _lrotr
Example
/* Example of _rotl, _rotr */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 unsigned value = 0x01234;

 printf("value = %016b\n\n", value);

 printf("left 2 = %016b\n",
        _rotl(value, 2));

 printf("left 4 = %016b\n",
        _rotl(value, 4));

 printf("left 6 = %016b\n",
        _rotl(value, 6));

 printf("left 8 = %016b\n\n",
        _rotl(value, 8));

 printf("right 2 = %016b\n",
        _rotr(value, 2));

 printf("right 4 = %016b\n",
        _rotr(value, 4));

 printf("right 6 = %016b\n",
        _rotr(value, 6));

 printf("right 8 = %016b\n",
        _rotr(value, 8));
}
Output
value = 0001001000110100
left 2 = 0100100011010000
left 4 = 0010001101000001
left 6 = 1000110100000100
left 8 = 0011010000010010


right 2 = 0000010010001101
right 4 = 0100000100100011
right 6 = 1101000001001000
right 8 = 0011010000010010

_searchenv

Header
stdlib.h
Prototype
void _searchenv(const char *filename, const char *varname, char *pathname);
Description
The _searchenv function searches for the file in the filename argument, using the environment variable in the varname argument. If the file is found, the complete pathname is stored in the buffer pointed to by the pathname argument. You must ensure that the pathname buffer is large enough to contain the constructed path name. If the filename is not found, an empty, null-terminated string is copied to the pathname buffer.

When searching for a file, the _searchenv function searches first in the current working directory, and then looks through the directories specified by the varname environment variable.

The _searchenv function is case-sensitive, so be sure that the varname variable matches the case of the environment variable. Environment variable names are uppercase. Common environment variables are PATH, LIB, and INCLUDE.

Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
getenv _putenv
Example
/* Example of _searchenv */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
 char buf[_MAX_PATH];

 _searchenv("dmc.exe"," PATH", buf);

 if (strlen(buf) == 0)
  printf("dmc.exe not found\n");
 else
  printf("dmc.exe found in %s\n", buf);
}
Output
dmc.exe found in c:\dm\bin\dmc.exe

_splitpath

Header
stdlib.h
Prototype
void _splitpath(const char *path, char *drive, char *dir, char *name, char *ext);
Description
The _splitpath function splits the pathname pointed to by path into its components, and copies the components to the locations pointed to by the drive, dir, name, and ext arguments. The path argument must be of the form:

drive:\dir\subdir\name. ext

The function uses these conventions when copying components:

  • The drive argument includes the colon
  • The dir argument includes leading, trailing backslashes
  • The name argument will contain the filename
  • The ext argument will include the preceding period
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_fullpath _makepath
Example
/* Example of _splitpath */

#include <stdlib.h>
#include <stdio.h>

void main(int argc, char *argv[])
{
 char drive[_MAX_DRIVE];
 char dir[_MAX_DIR];
 char filen[_MAX_FNAME];
 char ext[_MAX_EXT];

 _splitpath(argv[0],drive,dir,filen,ext);

 printf("This program's path is split as:\n"
        "Drive: %s\n"
        "Directory: %s\n"
        "Filename: %s\n"
        "Extension: %s\n",
        drive, dir, filen, ext);
}

Output
This program's path is split as:
Drive: c:
Directory: \dm\examples
Filename: _splitpa
Extension: .exe

_stackavail

Header
malloc.h
Prototype
size_t _stackavail(void);
Description
The _stackavail function gets the size, in bytes, of the available stack space for dynamically allocating stack memory with _alloca.
Return Value
The available stack size, in bytes.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_alloca

_ultoa

Header
stdlib.h
Prototype
char *_ultoa(unsigned long value, char *string, int radix);
Description
The _ultoa function converts the value in the value argument to a null-terminated string. The result is stored in the location pointed to by the string argument. The string can be a maximum of 33 bytes long. The radix argument specifies the base of the value argument; the radix can range from 2 and 36.
Synonym
Function: ultoa
Return Value
A pointer to the converted string.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_itoa _ltoa
Example
/* Example of _ultoa */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 char buffer[64], *ptr;
 unsigned long value = 3123456789L;

 ptr = _ultoa(value, buffer, 2);
 printf("The number %lu in binary is
         \"%s\"\n", value, buffer);

 ptr = _ultoa(value, buffer, 8);
 printf("The number %lu in octal is
         \"%s\"\n", value, buffer);

 ptr = _ultoa(value, buffer, 16);
 printf("The number %lu in hex is
         \"%s\"\n",
         value, buffer);
}
Output
The number 3123456789 in binary is
"10111010001011000010101100010101" The number 3123456789 in octal is "27213025425" The number 3123456789 in hex is "ba2c2b15"

_winmajor

Header
stdlib.h
Prototype
extern unsigned char _winmajor;
Description
This variable specifies the major version number of the Windows in use. For example, the value of _winmajor running under Windows 3. 1 is 3.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_winminor

Header
stdlib.h
Prototype
extern unsigned char _winminor;
Description
This variable specifies the minor version number of the Windows in use. For example, the value of _winminor running under Windows 3. 1 is 10.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

_winver

Header
stdlib.h
Prototype
extern unsigned int _winver;
Description
This variable holds both the major and minor version numbers of the Windows in use. The high byte contains the major version, the low byte contains the minor version.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32

exit

Header
stdlib.h
Prototype
void exit(int exitstatus);
Description
exit calls functions logged by atexit, all static destructors (for C++ programs), flushes all output buffers, closes all output files and returns to the operating system with an exit status given by exitstatus. exit is the preferred function for C++ programs. exitstatus is normally a EXIT_SUCCESS to indicate a normal end of program and EXIT_FAILURE to indicate an error. Only the lower order byte of exitstatus is returned to the parent process. The exit status can be referenced by the spawn return values.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
abort _exit _spawn
Example
See _exit

exit_pushstate

Header
exitstat.h
Prototype
int exit_pushstate(int retval);
int exit_popstate(void);
Description
Allows trapping calls to exit.

exit_pushstate saves the current state of the list maintained by the atexit function, creating a new one --a new "exit state". exit return points are then intercepted and controlled to return to the position in the code of the last use of exit_pushstate. The exit state is then popped, returning the atexit list to its previous value. If an exit_popstate is encountered before a call to exit, the exit state returns to the last pushed value.

These functions can conveniently convert stand-alone programs to subroutines. First, use exit_pushstate to set the return point from exit, providing an integer value that will inform the caller of the return value from exit calls in the former stand-alone program. Second, set up an if statement to test if the value of retval is 0. This value indicates that a call to the new subroutine has not been made yet. Call the former stand-alone program's main function. Calls to exit in the former stand-alone will return to the point at which exit_pushstate was called, with retval set to the return from the exit function plus 1. Subtract 1 from the retval to obtain the actual return value. If the subordinate function never calls exit, the function will return like a normal C function, at which point exit_popstate should be called explicitly.

Functions registered with atexit in the new subroutine are called in last-in-first-out order before returning to the calling function. Up to 16 states can be pushed at one time; no more than 16 calls to former stand-alone programs may be on the program stack at any given time.

Return Value
The integer value retval will be set to the value returned by any calls to exit plus 1 encountered before a matching exit_popstate has been reached.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
exit atexit
Example
/* Example for exit_popstate */

#include <stdio.h>
#include <stdlib.h>
#include <exitstat.h>

void f1(void) {
 printf("f1 called\n");
}

void f2(void) {
 printf("f2 called\n");
}

void f3(void) {
 printf("f3 called\n");
}

int used_to_be_main(void) {
 printf("used_to_be_main called\n");
 printf("adding atexit functions\n");
 atexit(f3);
 atexit(f2);
 printf("exiting used_to_be_main\n");
 exit(123);
}

void main() {
 int return_from_exit;

 exit_pushstate(return_from_exit);
 if (return_from_exit == 0)
 {
    used_to_be_main();
    exit_popstate();
 }
 else
    --return_from_exit;
 atexit(f1);
 printf("return_from_exit = %d\n",
        return_from_exit);
}
Output
used_to_be_main called
adding atexit functions
exiting used_to_be_main
f2 called
f3 called
return_from_exit = 123
f1 called

abort

Header
stdlib.h
process.h
Prototype
void abort(void);
Description
The abort function terminates the currently executing program. It is the same as a function call to _exit with a non-zero status.
Return Value
abort can be intercepted using the signal SIGABRT (see the function signal). abort does not flush the buffers nor does it call C++ static destructors. It is preferable to use exit rather than abort for C++ programs.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_c_exit _cexit exit _exit raise
Example
/* Example for abort */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 char input;

 printf("Enter 'a' to abort:");
 while (1)
 {
    scanf("%c",& input);
    if (input == 'a')
    {
      printf("Aborting...\n");
      abort();
    }
 }
}
Output
Enter 'a' to abort: a
Aborting...

atexit

Header
stdlib.h
Prototype
int atexit(void (__cdecl *func)(void));
int __far _fatexit(void (__cdecl __far *func)(void));
Description
atexit registers the function func. When the program terminates normally by returning from main or by calling exit, the function is called. A maximum of 32 functions can be registered by successive calls to the atexit function. Registered functions are passed no arguments and no values are returned. The far version of atexit is _fatexit.

The registered functions must have "C" linkage, the default linkage for C functions. Functions compiled with the C++ compiler must specify that they have "C" linkage in order to be registered with atexit. See the example.

When exit is called (either explicitly or via a return from main):

  1. Functions registered via atexit are called in the re-verse order that they were registered. (last in, first out)
  2. If this is a C++ program, the static destructors are called.
  3. All open streams are flushed and closed.
  4. _exit is called with the exit status, which returns to the operating system.
The _fatexit function is a far version of atexit; it can be used with any memory model.
Return Value
Returns 0 if func was successfully registered; otherwise non-zero if no more room exists for the function to be registered.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
exit _exit
Example
/* Example of atexit */

#include <stdio.h>
#include <stdlib.h>


#if __cplusplus
extern "C" { /* force c linkage */
#endif

void xfunc1(void)
{
  printf("xfunc1() called.\n");
}

void xfunc2(void)
{
  printf("xfunc2() called.\n");
}

#if __cplusplus
}
#endif

void main()
{
 atexit(xfunc1);
 atexit(xfunc2);
}
Output
xfunc2() called.
xfunc1() called.

atof

Header
stdlib.h
math.h
Prototype
double atof(const char *nptr);
Description
The atof function converts the string pointed to by nptr into a double-precision floating-point number. The string may have leading spaces, tabs, and + or -. Conversion stops on the first unrecognized character. If there are no recognized characters, the result is 0.
Return Value
Returns the double value derived from converting the string. Zero is returned if the input string has no recognizable characters.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
atoi atol _ecvt _fcvt scanf strtol
Example
/* Example of atof      */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 char *test1 = "3.141593";
 char *test2 = "123.5e15unrecognized 'u'";
 double result;

 result = atof(test1);
 printf("test1 is %g\n", result);

 result = atof(test2);
 printf("test2 is %g\n", result);
}
Output
test1 is 3.14159
test2 is 1.235e+017

atoi

Header
stdlib.h
Prototype
int atoi(const char *nptr);
long atol(const char *nptr);
long atoll(const char *nptr);
Description
These functions convert a string to an integer. They are equivalent to:
atoi (int)strtol(nptr, (char **)NULL, 10);
atol strtol(nptr, (char **)NULL, 10);
atoll strtoll(nptr, (char **)NULL, 10);
Return Value
Returns the integer value derived from converting the string. Zero is returned if the input string has no recognizable characters.
Compatibility
ANSI C99 7.20.1.2, DOS, Windows 3.x, Phar Lap, DOSX, Win32
See Also
atof _atold _ecvt _fcvt scanf strtol
Example
/* Example of atoi */

#include <stdio.h>
#include <stdlib.h>

void main()
{
  int result;
  char *test1 = "310";
  char *test2 = "No Number";

  result = atoi(test1);
  printf("Test1 is %d\n", result);

  result = atoi(test2);
  printf("Test2 is %d\n", result);
}
Output
Test1 is 310
Test2 is 0

bsearch

Header
stdlib.h
search.h
Prototype
void *bsearch(const void *key, const void *base, size_t num, size_t width, int(*cmp)(const void *elem1, const void *elem2));
Description
bsearch performs a binary search of a sorted array of num elements, which is pointed to by base, for an element that matches key. Contents of the array must have been previously sorted into ascending order. Each item of the array is width bytes. The function used in the search is pointed to by cmp; it must be supplied by the programmer and must be declared as taking C linkage. The cmp function takes two arguments as pointers to the element in the array. The cmp function must return one of the following values:
Return a value If
< 0 elem1 is less than elem2
= 0 elem1 and elem2 match
> 0 elem1 is greater then elem2
The standard library function strcmp is a suitable compare function for C-style strings.
Return Value
Returns a pointer to the matching element, or NULL if not found.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_lsearch
Example
/* Example for bsearch  */

#include <stdio.h>
#include <stdlib.h>

#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))

int array[] = { 15,117,232,332,456,567,678,789};

#ifdef __cplusplus
extern "C"
#endif

int intcmp(const void *p1, const void *p2)
{
  return(*(int *) p1 -*(int *) p2);
}

void main()
{
 int *pointer;
 int key = 567;

 pointer = (int *)bsearch(&key, array,
      SIZE(array), sizeof(int), intcmp);

 if (pointer)
  printf("[%d] is in array\n", key);
 else
  printf("[%d] is not in array\n", key);
}
Output
[567] is in array

calloc

Header
stdlib.h
Prototype
void *calloc(size_t num, size_t size);
void __far *_fcalloc(size_t num, size_t size);
void __near *_ncalloc(size_t num, size_t size);
Description
The calloc functions allocate a block of memory that is num * size bytes in size from the program heap. The memory is cleared (i. e. all bytes are initialized to zero) and a pointer to it is returned. The calloc function allocates storage space from the heap associated with the program's data model. The _fcalloc function allocates storage from the far heap (outside the default data segment). The _ncalloc function allocates storage from the near heap (inside the default data segment.)

If an error occurs (e. g. insufficient memory), NULL is returned. If either num or size is 0, NULL is returned. If a memory block larger than 64K is required, the X memory model should be used. Memory is dynamically allocated from the heap at run time, and must be freed explicitly if the space is required again within the program.

Return Value
A pointer to the allocated memory is returned on success, otherwise a NULL pointer is returned.
Compatibility
DOS Windows 3.x Phar Lap/ DOSX Win32
See Also
free Functions malloc Functions realloc Functions farcalloc
Example
/* Example for calloc */

#include <dos.h>
#include <stdio.h>
#include <stdlib.h>

#define num 50

/* compile with large data model */

void main()
{
 long *buffer;

 buffer = calloc (num, sizeof(long));
 if (buffer == NULL)
 {
    fprintf(stderr, "Calloc failed");
    abort();
 }

 printf("Memory allocated at offset:%x\n",
        buffer);
 free(buffer);
}
Output
Memory allocated at offset: ee

coreleft

Header
stdlib.h
Prototype
// For tiny, small, and medium models:
unsigned coreleft(void);

// For compact, large, and huge models:
unsigned long coreleft(void);
Description
The coreleft function returns the amount of RAM not in use.
Return Value
For tiny, small, and medium models, the amount of unused memory between the top of the heap and the stack is returned.

For compact, large, and huge models, the amount of unused memory between the highest allocated block and the end of available memory is returned.

Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
farcoreleft
Example
/* Example for coreleft */

#include <stdio.h>
#include <alloc.h>

void main()
{
 printf("There is %lu core left\n",
         (unsigned long) coreleft());
}
Output
There is 524287 core left

errno

Header
errno.h
Prototype
extern int errno;
Description
This variable is set to an error code when an error occurs in certain functions. The error codes are independent of the operating system. If a function sets errno the indication for it is in the entry for the function. To print the error message associated with the errno value, use the perror function. To access the error message string without printing use strerror or _strerror.

Variable errno can have many values but only a subset of them are actually set by the functions. The entire list of values is shown here; those that are not set by functions show NS, for not set. Also, some of the values are for Win32 only. These are marked here as Win32. The errno values that are used and the error messages that the perror function outputs for each constant are:

E2BIG Argument list too long
EACCES Permission denied
EAGAIN Resource temporarily unavailable Win32
EBADF Bad file descriptor
EBUSY NS Resource device
ECHILD No child process Win32
EDEADLOCK Resource deadlock avoided
EDOM Domain error
EEXIST File exists
EFAULT NS Bad address
EFBIG NS File too large
EILSEQ NS Illegal byte sequence
EINTR NS Interrupted function call
EINVAL Invalid argument
EIO NS Input/ output error
EISDIR NS Is a directory
EMFILE Too many open files
EMLINK NS Too many links
ENAMETOOLONG NS Filename too long
ENFILE NS Too many open files in system
ENODEV NS No such device
ENOENT No such file or directory
ENOEXEC Exec format error
ENOLCK NS No locks available
ENOMEM Not enough space
ENOSPC No space left on device
ENOSYS NS Function not implemented
ENOTDIR NS Not a directory
ENOTEMPTY Directory not empty Win32
ENOTTY NS Inappropriate I/ O control operation
ENXIO NS No such device or address
EPERM Operation not permitted Win32
EPIPE Broken pipe Win32
ERANGE REsult too large
EROFS NS Read-only file system
ESPIPE NS Invalid seek
ESRCH NS No such process
EXDEV Improper link
EZERO NS No error
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_doserrno _sys_errlist _sys_nerr strerror _strerror perror

expand

Header
malloc.h
Prototype
void *_expand(void *memblock, size_t size);
Description
The expand function attempts to enlarge or reduce the size of an allocated block of memory without moving its location in the heap. The size argument is the new block size in bytes.

Argument memblock points to the beginning of the block. It can also point to a freed block unless an intervening call to calloc, malloc, realloc, or _expand occur. When it points to a freed block, the block remains free after a call to _expand.

The function changes the size of the storage block in the data segment depending on the data model.

Return Value
Returns a void pointer to the reallocated memory block. The _expand function returns NULL if memory is insufficient to expand the block.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
calloc Functions malloc Functions realloc Functions free Functions
Example
/* Example for _expand,
 * malloc, _msize, strcat
 * _expand.c
 */

#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char const *const argv[])
{
 int i, total_size;
 char *args;

 args = malloc(10);
 if (args == NULL)
 {
   perror("Couldn't malloc");
   exit(EXIT_FAILURE);
 }
 *args = '\0';
 total_size = 1;
 for (i = 1; i < argc; i += 1)
 {
   total_size += strlen(argv[i]) + 1;
   if (total_size > _msize(args))
   {
     args = _expand(args, total_size);
     if (args == NULL)
     {
       puts("... Couldn't expand any more");
       exit(EXIT_FAILURE);
     }
     puts("... expanded...");
   }
   strcat(args, " ");
   strcat(args, argv[i]);
   puts(args);
 }
}
Output
c:\dm\examples>_expand here are some command line arguments
here
here are
... expanded...
here are some
... Couldn't expand any more

free

Header
stdlib.h
malloc.h
Prototype
void free(void *p);
void _ffree(void __far *p);
void _nfree(void __near *p);
Description
The free functions release the memory segment pointed to by p. The number of bytes that are freed is the number of bytes specified when the segment was allocated (or reallocated). The free function deallocates memory from the default data segment that has been allocated using calloc, malloc, or realloc. The _ffree function deallocates memory from the far heap that has been allocated using _fcalloc, _fmalloc, or _frealloc. The _nfree function deallocates memory from the near heap that has been allocated using _ncalloc, _nmalloc, or _nrealloc. The free functions do nothing if p is NULL.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap/ DOSX Win32
See Also
calloc malloc
Example
/* Example for free */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 char *p;
 if ((p = malloc(1000)) == NULL)
 {
  printf("Unable to allocate memory.\n");
  exit(EXIT_FAILURE);
 }
 printf("Allocated 1000 bytes. Freeing...\n");
 free (p);
 printf("Freed.\n");
}
Output
Allocated 1000 bytes. Freeing...
Freed.

getenv

Header
stdlib.h
Prototype
char *getenv(const char *name);
Description
getenv searches the environment list for a string of the form "varname=value", where varname is equal to name, and returns a pointer to the value string, if such a string is present. Comparisons are case-sensitive and environment names are usually uppercase.

Functions getenv and _putenv use global variable _environ to search for and modify the settings. Using _putenv to add or delete settings, changes the size of the environment table, and can also change the table's memory location, depending on memory requirements of the program. In these cases, _environ adjusts and points to the correct table location.

Return Value
Returns a pointer to the value string of an environment variable. A NULL return value means the name was not found in the environment.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_putenv
Example
/* Example for getenv */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 char *path;

 path = getenv("PATH");
 if (path == NULL)
   fprintf(stderr,"No PATH set\n");
 else
   printf("PATH=%s\n", path);
}
Output
PATH=y:.;c:\ndw;c:\dos;c:\;c:\windows;c:\dm\bin;z:.

abs

Header
stdlib.h
Prototype
int abs(int i);
long labs(long li);
long long llabs(long long lli);
Description
The abs functions return the absolute value of their arguments.
Return Value
Returns the absolute value.
Compatibility
ANSI C99 7.20.6.1, DOS, Windows 3.x, Phar Lap, DOSX, Win32
See Also
fabs Functions
Example
/* Example for labs */

#include <stdlib.h>
#include <stdio.h>

void main()
{
 long test, result;

 test = -314159L;
 result = labs(test);
 printf("The absolute value of
        (%ld) is (%ld)\n",
        test, result);
}
Output
The absolute value of (-314159) is (314159)

ldiv

Header
stdlib.h
Prototype
ldiv_t ldiv(long numerator, long denominator);
div_t div(int numerator, int denominator);
Description
The ldiv function divides the numerator by the denominator, returning the quotient and remainder. If the denominator is 0 the program will terminate with an error message.
Return Value
div returns a structure of type ldiv_t, containing both quotient and remainder: long quot, rem.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
div
Example
/* Example for ldiv */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 ldiv_t result;
 long numerator, denominator;

 printf("Enter the numerator: ");
 scanf("%ld", &numerator);
 printf("And denominator: ");
 scanf("%ld", &denominator);

 result = ldiv (numerator, denominator);
 printf("The quotient is %ld and the
         remainder is %ld\n",
         result.quot, result.rem);
}
Output
Enter the numerator: 45
And denominator: 7
The quotient is 6 and the remainder is 3

malloc

Header
stdlib.h
malloc.h
Prototype
void *malloc(size_t numbytes);
void __far *_fmalloc(size_t numbytes);
void __near *_nmalloc(size_t numbytes);
Description
The malloc functions allocate a block of memory that is numbytes in size. malloc allocates memory from the heap; _fmalloc allocates memory from the far heap; _nmalloc allocates memory from the near heap. If numbytes is 0, NULL is returned.

Memory allocated with malloc must be released back to the heap with the free function rather than with the delete operator. Memory allocated with _fmalloc must be released back to the heap with the _ffree function; memory allocated with _nmalloc must be released with the _nfree function.

Return Value
Pointer to the memory block allocated. NULL is returned if not enough memory is available, or if numbytes is 0.
Compatibility
DOS Windows 3. x Phar Lap/ DOSX Win32
See Also
calloc Functions free Functions realloc Functions
Example
/* Example for malloc */

#include <stdlib.h>
#include <stdio.h>
#define NUM_INTS 1024

void main()
{
 int *memblock;

 memblock = malloc(NUM_INTS * sizeof(int));
 if (memblock == NULL)
 {
   perror("Insufficient memory");
   exit(EXIT_FAILURE);
 }
 else
   printf("Memory allocated\n");
 free(memblock);
}
Output
Memory allocated

mblen

Header
stdlib.h
Prototype
int mblen(const char *s, size_t n);
int __far _fmblen(const char __far *s, size_t n);
Description
mblen returns the number of bytes in the multi-byte character that s points to. n is the maximum number of bytes to check in the character.

_fmblen is a model-independent (large-model) form of the mblen function.

Return Value
If s is not null, both functions return the number of bytes in the multi-byte character s. If s is null, or if the string that it points to does not contain a multi-byte character in the first n characters, both functions return -1.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbstowcs mbtowc wcstombs wctomb

mbstowcs

Header
stdlib.h
Prototype
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n);
size_t __far _fmbstowcs(wchar_t __far *pwcs, const char __far *s, size_t n);
Description
mbstowcs converts n or fewer multi-byte characters, from the s string, to a sequence of wide character codes. The resulting wide character string is stored in the array pcws. The wide character string in pcws is not null-terminated, unless a null character is encountered during conversion. If the s string contains a null character before n bytes, the null character is converted to a wide-character null character (L'\0').

_fmbstowcs is a model-independent (large-model) form of the mbstowcs function.

Return Value
The number of converted multi-byte characters. If either function encounters an invalid multi-byte character, it returns -1.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbtowc wcstombs wctomb
Example
See wcstombs

mbtowc

Header
stdlib.h
Prototype
int mbtowc(wchar_t *pwc, const char *s, size_t n);
int __far _fmbtowc(wchar_t __far *pwc, const char *s, size_t n);
Description
mbtowc converts the multi-byte character s to a corresponding wide character code (converting no more than n bytes), stores the code in the object pwc points to, and returns the length in bytes of the multi-byte character.

_fmbtowc is a model-independent (large-model) form of the mbtowc function.

Return Value
Both functions return the number of bytes copied, if successful. If s points to an invalid character, -1 is returned. If s is null, both functions return 0.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mbtowc wcstombs wctomb

_memmax

Header
stdlib.h
Prototype
size_t _memmax(void);
Description
The _memmax function returns the size in bytes of the largest contiguous block of memory that is available for allocation from the near heap (the default data segment).
Return Value
The block size is returned. If unsuccessful, 0 is returned, indicating that nothing more can be allocated from the near heap.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
malloc Functions _memavl _msize Functions
Example
/* Example of _memmax */

#include 
#include 
#include 

void main()
{
 long *ptr;
 printf("Largest contiguous block of
         memory is %u\n",
         _memmax());
 ptr = _nmalloc(1000 * sizeof(long));
 if (ptr != NULL)
 {
   printf("Now the largest block is %u\n",
          _memmax());
   _nfree(ptr);
 }
}
Output
Largest contiguous block of memory is 58992
Now the largest block is 54476

perror

Header
stdio.h
Prototype
void perror(const char *msg);
Description
Displays a message on the standard error output describing the last error that occurred in a system or library function call. The argument msg is printed first, then a colon, followed by the error description.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_strerror
Example
/* Example for perror */

#include <stdio.h>
#include <stdlib.h>

void main()
{
 FILE *fp;

 fp = fopen("perror.dat", "r");
 if (!fp)
  perror("Unable to open file for reading");
}
Output
Unable to open file for reading: No such file or directory

qsort

Header
stdlib.h
search.h
Prototype
void qsort(void *base, size_t nel, size_t size, int(__cdecl *compare)(const void *, const void*));
Description
The qsort function is an implementation of the quick-sort algorithm. It sorts a table of elements. The function arguments are:

Argument Description
base Points to the element at the base of the table.
nel The number of elements in the table.
size The size in bytes of one table element.
compare The name of the comparison function.

The function compare must be written by the programmer and must return an integer that is less than, equal to, or greater than zero according to a comparison of the first argument to the second. compare should be declared as taking C linkage.

Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
Example
/* Example for qsort */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXL 10
unsigned char *line[MAXL];

#ifdef __cplusplus
extern "C"
#endif

// Compare function sorts by pointers not arrays

int comp(const void *a, const void *b)
{
 return strcmp(*(char **)a, *(char **)b);
}

int main()
{
 int j, k:
 unsigned char buffer[82];
 printf("Enter 10 strings to sort\n");
 for (j = 0; j < MAXL; ++j)
 {
   printf("String %d: ", j + 1);
   if (!fgets((char *)buffer, 80, stdin))
     break;
   line[j] = malloc(strlen((char *)buffer)+1);
   strcpy((char *)line[j],(char *)buffer);
 }
 printf("\n\n\nSorting ten lines from stdin:\n");
 qsort(line, j, sizeof(unsigned char *), comp);

 for (k = 0; k < j; k++)
   printf("Line %d: %s", k + 1, line[k]);
 return EXIT_SUCCESS;
}
}
Output
Enter 10 strings to sort
String 1: red
String 2: green
String 3: orange
String 4: blue
String 5: white
String 6: cyan
String 7: brown
String 8: black
String 9: purple
String 10: yellow

Sorting ten lines from stdin...
Line 1: black
Line 2: blue
Line 3: brown
Line 4: cyan
Line 5: green
Line 6: orange
Line 7: purple
Line 8: red
Line 9: white
Line 10: yellow

rand

Header
stdlib.h
Prototype
int rand(void);
Description
rand returns a random number in the range 0 to RAND_MAX. srand seeds the random number generator.
Return Value
An integer containing the random number.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
srand random
Example
/* Example for rand, srand.
 * Simulates the throwing of
 * three dice
 */

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int dieroll()
{
 return (rand() % 6) + 1;
}

void main()
{
 int total = 0, die, nd;
 srand((int)time(NULL));

 for (nd = 0; nd < 3; nd++)
 {
  die = dieroll();
  total += die;

  printf("Die roll %d: %d\n",
         nd + 1, die);
 }
 printf("\nThe total of the three dice is
         %d.\n", total);
}
Output
Die roll 1:2
Die roll 2:2
Die roll 3:5

The total of the three dice is 9.

random

Header
stdlib.h
Prototype
int random(int num);
Description
The random function generates a random number between 0 and the upper limit specified in the num argument.
Return Value
A random number between 0 and num-1.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
rand randomize
Example
/* Example for random, randomize
 * Simulates the throwing of three dice
 */

#include <stdlib.h>
#include <stdio.h>

int dieroll ()
{
 return random(6) + 1;
}

void main()
{
 int total = 0, die, nd;

 randomize();

 for (nd = 0; nd < 3; nd++)
 {
   die = dieroll();
   total += die;

   printf("Die roll %d: %d\n", nd + 1, die);
 }
 printf("\nThe total of the three dice is
         %d.\n", total);
}
Output
Die roll 1:1
Die roll 2:1
Die roll 3:6

The total of the three dice is 8.

randomize

Header
stdlib.h
Prototype
void randomize(void);
Description
The randomize function initializes the random number generator with a random value obtained by calling function time. Because randomize calls time, include the time.h file in your program.
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
rand random
Example
See random

realloc

Header
stdlib.h
malloc.h
Prototype
void *realloc (void *ptr, size_t size);
void __far *_frealloc(void __far *ptr, size_t size);
void __near *nrealloc(void __near *ptr, size_t size);
Description
The realloc family functions change the size of a previously allocated memory block pointed to by ptr. The size of the block after the call to realloc is specified by size. If size is 0, ptr is free'd and NULL is returned. If ptr is NULL, then size is malloc'd and the result is returned. If there is insufficient room to expand the current block, a new block will be allocated and the current block released. Existing data will be copied into the new block.

The realloc function reallocates memory in the default heap; _frealloc reallocates memory in the far heap; _nrealloc reallocates memory in the near heap.

Return Value
Returns a pointer to the reallocated memory block. Returns NULL (but ptr is not freed) if memory is insufficient for the realloc.
Compatibility
DOS, Windows 3.x, Phar Lap/ DOSX, Win32
See Also
calloc Functions free Functions malloc Functions
Example
/* Example for realloc */

#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char const *const argv[])
{
 int i;
 unsigned total_size;
 char *arg_string;

 arg_string = malloc (10);
 if (arg_string == NULL)
 {
   perror("Couldn't malloc");
   exit(EXIT_FAILURE);
 }
 *arg_string = '\0';
 /* at least 1 for the null char at the end */
 total_size = 1;
 for (i = 1; i < argc; i += 1)
 {
   /* + 1 for the blank */
   total_size += strlen(argv[i]) + 1;
   if (total_size > _msize(arg_string))
   {
     arg_string = realloc(arg_string,
                   total_size);
     if (arg_string == NULL)
     {
       puts("... Couldn't expand any more");
       exit(EXIT_FAILURE);
     }
     puts("... expanded...");
   }
   strcat(arg_string, " ");
   strcat(arg_string, argv[i]);
   puts(arg_string);
 }
}

Output
 Now
 Now is
 ... expanded...
 Now is the
 ... expanded...
 Now is the time
 ... expanded...
 Now is the time for
 ... expanded...
 Now is the time for all
 ... expanded...
 Now is the time for all good
 ... expanded...
 Now is the time for all good men
 ... expanded...
 Now is the time for all good men ...

srand

Header
stdlib.h
Prototype
void srand(unsigned seed);
Description
srand initializes the random number generator rand with a seed number. If srand is never called, the default is srand(1).
Return Value
None
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
Example
See rand

strtof

Header
stdlib.h
Prototype
float strtof(const char *nptr, char ** endptr);
double strtod(const char *nptr, char ** endptr);
Description
Converts the character representation of a floating-point value to a float or double. The function assumes that the input string (pointed to by nptr) is in the same format as a literal floating-point constant. The first character encountered that cannot be a part of a literal floating-point constant terminates the translation process. The address of the terminating character is assigned to the pointer variable pointed to by endptr. ±NAN and ±INF are valid input values representing NaN and infinity.
Return Value
A float or double value based on the string pointed to by nptr.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
atof scanf
Example
/* Example for strtod */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void main()
{
 char str[80];
 char *endptr;
 double d;

 printf("Enter a string for double
         conversion: ");
 gets(str);

 d = strtod(str, &endptr);
 if (endptr == str)
  printf("That is not a valid string\n");
 else
 {
  printf("The converted float is %g\n", d);
  if (strlen(endptr) != 0)
   printf("The remaining string from your
           input is \"%s\"\n", endptr);
 }
}
Output
Enter a string for double conversion: 100
bottles of beer on the wall
The converted float is 100
The remaining string from your input is "
bottles of beer on the wall"

strtol

Header
stdlib.h
inttypes.h
Prototype
long strtol(const char *nptr, char **endptr, int base);
unsigned long strtoul(const char *nptr, char **endptr, int base);
long long strtoll(const char *nptr, char **endptr, int base);
unsigned long long strtoull(const char *nptr, char **endptr, int base);

long wcstol(const wchar_t *nptr, wchar_t **endptr, int base);
unsigned long wcstoul(const wchar_t *nptr, wchar_t **endptr, int base);
long long wcstoll(const wchar_t *nptr, wchar_t **endptr, int base);
unsigned long long wcstoull(const wchar_t *nptr, wchar_t **endptr, int base);

#include <inttypes.h>
intmax_t strtoimax(const char *nptr, char **endptr, int base);
uintmax_t strtoumax(const char *nptr, char **endptr, int base);
intmax_t wcstoimax(const wchar_t *nptr, wchar_t **endptr, int base);
uintmax_t wcstoumax(const wchar_t *nptr, wchar_t **endptr, int base);
Description
The strtol functions convert a string pointed to by nptr to an integer value. During conversion, the functions recognize a string of digits with the following form:
[whitespace] [sign] [0] [{ x | X } ] [digits]
The function stops reading the string at the first character that does not represent a part of the number. A pointer to that character will be stored into *endptr, if endptr is not NULL.

base is the numerical base of the conversion, which can be from 2 through 36. If it is 0, the format of the string determines the base. If the leading character is 0 and the second character is not x or X, the string is interpreted as octal. If the first character is 0 and the second character is x or X it will be interpreted as a hexadecimal integer.

If the leading character is 1 through 9, the string is interpreted as a decimal integer. The upper or lower case letters A to Z are assigned values 10 through 35. Only letters with values less than the base are permitted.

Return Value
If the value overflows, then errno is set to ERANGE and a value is returned from the following table. For signed functions, the sign determines if it is the MAX or MIN value:
strtol LONG_MAX or LONG_MIN
strtoul ULONG_MAX
strtoll LLONG_MAX or LLONG_MIN
strtoull ULLONG_MAX
wcstol LONG_MAX or LONG_MIN
wcstoul ULONG_MAX
wcstoll LLONG_MAX or LLONG_MIN
wcstoull ULLONG_MAX
strtoimax INTMAX_MAX or INTMAX_MIN
strtoumax UINTMAX_MAX
wcstoimax INTMAX_MAX or INTMAX_MIN
wcstoumax UINTMAX_MAX
If an unrecognized character is encountered before a legal character, zero is returned.
Compatibility
ANSI C99 7.8.2.3, 7.8.2.4, 7.20.1.4, 7.24.4.1.1, DOS, Windows 3.x, Phar Lap, DOSX, Win32
Note: long long forms are not supported by 16 bit memory models. Wide character forms are only in Win32.
See Also
atoi atol atoll scanf strtold
Example
/* Example for strtol */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void main()
{
 char str[80];
 char *endptr;
 long int i;

 printf("Enter a string for long int conversion: ");
 gets(str);

 i = strtol(str, &endptr, 0);
 if (endptr == str)
  printf("That is not a valid string\n");
 else
 {
  printf("The converted long int is %d\n", i);
  if (strlen(endptr) != 0)
   printf("The remaining string from your input is \"%s\"\n", endptr);
 }
}
Output
Enter a string for long int conversion: 0x64
bottles of beer on the wall
The converted long int is 100
The remaining string from your input is "bottles of beer on the wall"

strtold

Header
stdlib.h
Prototype
long double strtold(const char *nptr, char **endptr);
Description
The strtold function converts an ASCII string pointed to by nptr to a long double value and recognizes a string of the form:
[whitespace] [sign] [digits] [.digits] [{ d | D | e | E } [sign] digits]
A whitespace, which consists of space and tab characters, is ignored; sign is either plus (+) or minus (-); and digits are one or more decimal digits. If no digits appear before the decimal point, at least one must appear after the decimal point. The decimal digits can be followed by an exponent, which consists of an introductory letter and optionally signed decimal integer.
Synonym
Function: strtold
Return Value
Returns the value of the floating-point number, except when this would cause an overflow. In this case, the function returns plus (+) or minus (-) HUGE_VAL. The function returns 0 if no conversion could be performed or if an underflow occurred.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
atoi, atol, scanf, strtol

system

Header
stdlib.h
process.h
Prototype
int system(const char *string);
Description
system causes string to pass to the operating system command processor as if the string had been typed in at the console. The current program waits until the command is executed and then resumes. The exit status of programs run using system, cannot be determined. Use one of the spawn functions if an exit status is required. system cannot be used to set environment variables.
Return Value
If there was not enough available memory to execute the process, then -1 is returned. Otherwise, a 0 is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
_exec
_spawn
Example
/* Example for system */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <direct.h>

void prompt ()
{
 char path[_MAX_DIR];

 _getcwd(path, _MAX_DIR);
 printf("%s>", path);
}

int execute (char *command)
{
 int res = 0;

 _strupr(command);
 if (strstr(command, "DEL") == command)
  printf("You do not have rights to do
          that.\n\n");
 else if (strstr(command, "FORMAT") ==
        command)
  printf("You do not have rights to do
          that.\n\n");
 else if (strstr(command, "EXIT ALPHA") ==
          command)
  res = 1;
 else
  system(command);

 return res;
}

void main()
{
 int res;
 char command[128];

 do
 {
    prompt();
    gets(command);

    res = execute(command);
 } while (!res);
}
Output
C:\DM\BIN> dir *.ini

Volume in drive C is
Volume Serial Number is 1CD4-5ECB
Directory of C:\DM\BIN

TOOLS   INI       610   06-10-94        11:34a
SRT     INI     7,949   06-11-94        10:41a
PENWIN  INI       396   12-07-92         3:10a
PRJMGR  INI       143   06-21-94         9:14a

4 file(s)                     9,098 bytes
                        102,592,512 bytes free

C:\DM\BIN> del *.ini
You do not have rights to do that.

C:\DM\BIN>

_tolower

Header
ctype.h
Prototype
int _tolower(int c); int tolower(int c);
int _toupper(int c); int toupper(int c);

Description
The tolower function converts any integer value c in the range of 'A' -'Z' to lowercase. The _tolower function is special version of tolower which is intended for use only when c is uppercase. If _tolower encounters a value that is not an uppercase letter, the result is undefined.

toupper converts to uppercase the integer value c in the range of 'a' -'z'. Function _toupper is a special version of toupper that is intended for use only when c is lowercase. If _toupper encounters a value that is not a lowercase letter, the result is undefined.

These functions are implemented as macros in ctype.h, and are also included as functions within the library. Undefining the macros, or not including ctype.h, defaults to usage of the library functions.

Return Value
tolower returns c, converted to lower case if it was uppercase, otherwise c is returned unchanged. toupper returns c, converted to upper case if it was lower case, otherwise c is returned unchanged. If _tolower and _toupper encounter an invalid character, the result is undefined.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
Example
/* Example for tolower,
   _toascii, _tolower,
   toupper, _toupper
 */

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

void main()
{
 char *str = "Row, Row Row Your Boat...";
 char *p;

 printf("The original string: \"%s\"\n", str);

 printf("After running tolower on each
         character: \"");
 for (p = str; *p; p++)
    printf("%c", tolower(*p));
 printf("\"\n");

 printf("After running toupper on each
         character: \"");
 for (p = str; *p; p++)
    printf("%c", toupper(*p));
 printf("\"\n");
}
Output
The original string: "Row, Row Row Your Boat..."
After running tolower on each character: "row,
row row your boat..."
After running toupper on each character: "ROW,
ROW ROW YOUR BOAT..."

wcstombs

Header
stdlib.h
Prototype
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n);
size_t __far _fwcstombs(char __far char *s, const wchar_t __far *pwcs, size_t n);
Description
wcstombs converts the sequence of wide character codes pwcs to
a multi-byte character string, stores it in the array s points to, and returns the number of array elements changed.

_fwcstombs is a model-independent (large-model) form of the wcstombs function.

Return Value
The number of wide characters copied.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
mblen mbstowcs mbtowc wctomb

wctomb

Header
stdlib.h
Prototype
int wctomb(char *s, wchar_t wchar);
int __far _fwctomb(char __far *s, wchar_t wchar);
Description
wctomb converts wchar to a multi-byte character, stores it in the array s points to, and returns the length in bytes of the wide character.

_fwctomb is a model-independent (large-model) form of the wctomb function.

Return Value
If successful, both functions return the number of bytes copied. If conversion is not possible, -1 is returned. If wchar is the wide-character null character, 0 is returned.
Compatibility
DOS Windows 3.x Phar Lap DOSX Win32
See Also
wcstombs mbstowcs mbtowc
Home | Compiler & Tools | IDDE Reference | STL | Search | Download | Forums