Microsoft C RunTime Library Reference
Microsoft C RunTime Library Reference
All rights reserved. No part of the contents of this book may be reproduced or trans
mitted in any form or by any means without the written permission of the publisher.
Includes index.
1. C (Computer program language) 2. Microsoft C
(Computer program) 3. Macro instructions (Electronic
computers) I. Microsoft.
QA76.73.Cl5M52 1990 005.13'3 89-12240
ISBN 1-55615-225-6
2 3 4 5 6 7 8 9 HCHC 3 2 I 0
Distributed to the book trade outside the United States and Canada by Penguin
Books Ltd.
Microsoft, the Microsoft logo, MS-DOS, QuickC, and XENIX are registered trademarks
and Windows is a trademark of Microsoft Corporation.
AT&T and UNIX are registered trademarks of American Telephone and Telegraph
Company.
Hercules is a regi�tered trademark of Hercules Computer Technology.
IBM is a registered trademark of International Business Machines Corporation.
Olivetti is a registered trademark of Ing. C. Olivetti.
Contents
Introduction . . . v
About the C Run-Time Library • v
About This Book . . . vii
Other Books of Interest vii
Document Conventions ,ix
Special Offer . . . . . xi
Iii
Iv Microsoft C Run-Time Library Reference
Alp habeticFunctionReference . . . . . . . . . • • • . 76
Index . . . . . . . . . . . . . . . . . . . . . . . • • • 829
Introduction
The Microsoft® C Run-Time Library is a set of over 500 ready-to-use functions
and macros designed for use in C programs. The run-time library makes program
ming easier by providing
The C run-time library is important because it provides basic functions not pro
vided by the C language itself. These functions include input and output, memory
allocation, process control, graphics, and many others.
This book describes the Microsoft C run-time library routines included with the
Microsoft Professional Development System version 6.0. These comprise all of
the routines included with earlier versions of Microsoft C, as well as many new
routines.
NOTE Microsoft documentation uses the term "OS/2" to refer to the OS/2 systems
Microsoft Operating System/2 (MS® 0512) and IBM@ OS/2. Similarly, the term "DOS" refers
to both the MS-DOS® and IBM Personal Computer DOS operating systems. The name of a
specific operating system is used when It is necessary to note features that are unique to
that system.
v
vi Microsoft C Run-Time Library Reference
ANSI C Compatibility
The C run-time library routines are designed for compatibility with the ANSI C
standard, which Microsoft C compilers support. The major innovation of ANSI C
is to permit argument-type lists in function prototypes (declarations). Given the
information in the function prototype, the compiler can check later references to
the function to make sure that the references use the correct number and type of
arguments and the correct return value.
To take advantage ofthe compiler's type-checking ability, the include files that
accompany the C run-time library have been expanded. In addition to the defini
tions and declarations required by library routines, the include files now contain
function declarations with argument-type lists. Several new include files have
also been added. The names of these files are chosen to maximize compatibility
with the ANSI C standard and with XENIX and UNIX names.
The fonts library allows your programs to display various styles and sizes of text
in graphics images or charts. You can use font-manipulation routines with any
graphics routines that display text, including presentation graphics.
This book has two parts. Part I, "Overview," introduces the Microsoft C library.
It describes general rules for using the library and summarizes the main catego
ries of library routines. Part I contains the following chapters:
The following books cover a variety of topics that you may find useful. They are
listed only for your convenience. With the exception of its own RUblications,
Microsoft does not endorse these books or recommend them over others on the
same subject.
I
• Harbison, Samuel P., and Guy L. Steele, Jr. C: A Reference Manual, 2d ed.
Englewood Cliffs, NJ: Prentice Hall, 1987.
A comprehensive guide to the C language and the standard library.
• Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language,
2d ed. Englewood Cliffs, NJ: Prentice Hall, 1988.
The first edition of this book is the classic definition of the C language. The
second edition includes new information on the proposed ANSI C standard.
• Lafore, Robert. Microsoft C Programmingfor the IBM. Indianapolis, IN:
Howard W. Sams & Company, 1987.
The first half of this book teaches C. The second half concentrates on specif
ics of the PC environment, such as BIOS calls, memory, and video displays.
• Mark Williams Company. ANSI C: A Lexical Guide. Englewood Cliffs, NJ:
Prentice Hall, 1988.
A dictionary-style guide to the ANSI C standard.
• Plauger, P. J., and Jim Brodie. Standard C. Redmond, WA: Microsoft Press,
1989.
A quick reference guide to the ANSI C implementation by the secretary and
chairman of the ANSI-authorized C Programming Language Standards
Committee.
Introduction ix
• Plum, Thomas. Reliable Data Structures in C. Cardiff, NJ: Plum Hall, 1985 .
•
Docu111ent Convenllons
This book uses the following document conventions :
Example Description
STDIO.H Uppercase letters indicate file names, segment
names, registers, and tenns used at the
operating-system command level.
far Boldface letters indicate C keywords, operators,
language-specific characters, and library routines.
Within discussions of syntax, bold type indicates
that the text must be entered exactly as shown.
8
expression Words in italics indicate placeholders for infonna-
tion you must supply, such as a file name. Italics are
also occasionally used for emphasis in the text.
[option]) Items inside double square brackets are optional.
x Microsoft C Run-Time Library Reference
#pragma pack { 112} Braces and a vertical bar indicate a choice among
two or more items. You must choose one of these
items unless double square brackets surround the
braces.
//:include <io. h > This font is used for examples, user input, program
output, and error messages in text.
C L options' [files ...]J Three dots following an item indicate that more
items having the same form may appear.
w h i l e() A column of three dots tells you that part of the ex
{ ample program has been intentionally omitted.
CTRL+ENTER Small capital letters are used for the names of keys
on the keyboard. When you see a plus sign (+) be
tween two key names, you should hold down the
first key while pressing the second.
The carriage-return key, sometimes marked as a
bent arrow on the keyboard, is called ENTER.
"argument" Quotation marks enclose a new term the first time it
is defined in text.
"C string" Some C constructs, such as strings, require quotation
marks. Quotation marks required by the language
n II I I t t•
have the form and rather than " " and
Color Graphics The first time an acronym is used, it is often
Adapter (CGA) spelled out.
Introduction xi
If you have questions or comments about the files on the disk, send them to:
Languages User Education, Microsoft Corporation, One Microsoft Way,
Redmond, WA 98052-6399.
Overview
Overview
The first part of this book provides an overview of the run-time
library provided with the Microsoft C Professional Development
System.
This chapter provides basic information about how to use Microsoft C library
routines. It also describes some special rules, such as file- and path-name conven
tions, that apply to particular routines. You should read this chapter before you
begin to use C library routines, and you may also want to refer back to it if you
have questions about library procedures.
#include <stdio.h>
main( l
(
printf( "Microsoft C" );
The program prints Mi c r o soft C by calling the printf routine, which is part
of the standard C library. Calling a library routine normally involves two groups
of files:
Header files and library files are both included with Microsoft C. Header files are
used when compiling, and library files are used when linking.
5
6 Microsoft C Run· Time Library Reference
You include the necessary header files in your program source code with
#include directives. The description of each library routine in Part 2, "Refer
ence," tells you what header file the routine requires. Since printf requires the
STDIO.H header file, the SAMPLE.C program contains the following line:
#i n c l u d e < s t d i o . h >
This line causes the compiler to insert the contents of STDIO.H into the source
file SAMPLE.C.
After you compile the source file, you link the resulting object (.OBJ) file with
the appropriate library (.LIB) file to create an executable (.EXE) file. Your object
file contains the name of every routine that your program calls, including library
routines. If a routine is not defined in your program, the linker searches for its
code in a library file and includes that code in the �xecutable file.
Normally, the code for standard library routines is contained in the "default li
brary" that you create when installing Microsoft C. Since the linker automat
ically searches the default library, you do not need to specify that library's name
when linking your program. The following command links the example program
with the default library:
l i n k s a mpl e , , , ;
If you call a library routine that is not contained in the default library, you must
give the linker the name of the library file that contains the routine. For instance,
suppose your program uses a Microsoft C graphics routine and you did not make
GRAPHICS.LIB part of your default library when installing Microsoft C. You
would then link the program using a line like the following:
l i n k s a m p l e , , , g r a p hic s . l i b ;
For more information about libraries and linking, consult the installation docu
mentation for your compiler.
Definition Example
Macro If a library routine is implemented as a macro, the
macro definition appears in a header file. For in
stance, the toupper macro is defined in the header
file CTYPE.H.
Manifest constant Many library routines refer to constants that are de
fined in header files. For instance, the open routine
A function declaration lists the name of the function, its return type, and the num
ber and type of its arguments. For instance, below is the declaration of the pow
library function from the header file MATH.H:
double pow( double x , double y );
The example declares that pow returns a value of type double and takes two ar
guments of type double. Given this declaration, the compiler can check every ref
erence to pow in your program to ensure that the reference passes two double
arguments to pow and takes a return value of type double.
The compiler can perform type checking only for function references that appear
after the function declaration. Because of this, function declarations normally ap
pear near the beginning of the source file, prior to any use of the functions they
declare.
8 Microsoft C Run·Time Library Reference
Function declarations are especially important for functions that return a value of
some type other than int, which is the default. For example, the pow function re
turns a double value. If you do not declare such a function, the compiler treats its
return value as int, which can cause unexpected results.
It is also a good practice to provide declarations for functions that you write. If
you do not want to type the declarations by hand, you can generate them automat
ically by using the /Zg compiler option. This option causes the compiler to
generate ANSI-standard function declarations for every function defined in the
current source file. Redirect this output to a file, then insert the file near the
beginning of your source file.
Your program can contain more than one declaration of the same function, as
long as the declarations do not conflict. This is important if you have old pro
grams whose function declarations do not contain argument-type lists. For in
stance, if your program contains the declaration
c h a r *c a l l o c C >:
c h a r *c a l l o c C u n s i gn e d , u n s i gn e d ) ;
Because the two declarations are compatible, even though they are not identical,
no conflict occurs. The second declaration simply gives more information about
function arguments than the second. A conflict would arise, however, if the decla
rations gave a different number of arguments or gave arguments of different
types.
Some library functions can take a variable number of arguments. For instance,
the printf function can take one argument or several. The compiler can perform
only limited type checking on such functions, a factor that affects the following
library functions:
• In calls to cprintf, cscanf, printf, and scanf, only the first argument (the for
mat string) is type checked.
• In calls to fprintf, fscanf, sprintf, and sscanf, only the first two arguments
(the file or buffer and the format string) are type checked.
• In calls to open, only the first two arguments (the path name and the open
flag) are type checked.
• In calls to sopen, only the first three arguments (the path name, the open flag,
and the sharing mode) are type checked.
Using C Library Routines 9
• In calls to execl, execle, execlp, and execlpe, only the first two arguments
(the path name and the first argument pointer) are type checked.
• In calls to spawnl, spawnle, spawnlp, and spawnlpe, only the first three ar
guments (the mode flag, the path name, and the first argument pointer) are
type checked.
Case Sensitivity
The DOS and OS/2 operating systems are not case sensitive (they do not dis
tinguish between uppercase and lowercase letters). Thus, SAMPLE.C and
Sample.C refer to the same file in DOS and OS/2. However, the XENIX operat
ing system is case sensitive. In XENIX, SAMPLE.C and Sample.C refer to differ
ent files. To transport programs to XENIX, choose file and path names that work
correctly in XENIX, since either case works in DOS and OS/2. For instance, the
following directives are identical in DOS and OS/2, but only the second works in
XENIX:
# i n c l u d e < ST D I O . H >
#i ncl ude < s t d i o . h>
Subdirectory Conventions
Under XENIX, certain header files are normally placed in a subdirectory named
SYS. Microsoft C follows this convention to ease the process of transporting pro
grams to XENIX. If you do not plan to transport your programs, you can place
the SYS header files elsewhere.
Path-Name Delimiters
XENIX uses the slash (/) in path names, while DOS and OS/2 use the backslash
(\). To transport programs to XENIX, it is advantageous to use path-name
delimiters that are compatible with XENIX whenever possible.
·
10 Microsoft C Run-Time Library Reference
• Some macros treat arguments with side effects incorrectly when the macro
evaluates its arguments more than once (see the example that follows this
list). Not every macro has this effect. To determine if a macro handles side ef
fects as desired, examine its definition in the appropriate header file.
• A function name evaluates to an address, but a macro name does not. Thus,
you cannot use a macro name in contexts requiring a function pointer. For in
stance, you can declare a pointer to a function, but you cannot declare a
pointer to a macro.
• You can declare functions, but you cannot declare macros. Thus, the compiler
cannot perform type checking of macro arguments as it does of function argu
ments. However, the compiler can detect when you pass the wrong number of
arguments to a macro.
• You must always include the appropriate header file when using a library
macro. Every library macro is defined with a #define directive in a header
file. If you do not include the header file, the macro is undefined.
Using C Library Routines 1 1
The following example demonstrates how some macros can produce unwanted
side effects. It uses the toupper routine from the standard C library.
#i n c l u d e < c t y p e . h>
i n t a = 'm' ;
a = t o u p p e r ( a ++ ) ;
The definition uses the conditional operator (? :). The conditional expression
evaluates the argument c twice: once to check if it is lowercase and again to cre
ate the result. This macro evaluates the argument a++ twice, increasing a by 2
instead of 1. As a result, the value operated on by islower differs from the value
operated on by _toupper.
Like some other library routines, toupper is provided in both macro and function
versions. The header file CTYPE.H not only declares the toupper function but
also defines the toupper macro.
Choosing between the macro version and function version of such routines is
easy. If you wish to use the macro version, you can simply include the header file
that contains the macro definition. Because the macro definition of the routine al
ways appears after the function declaration, the macro definition normally takes
precedence. Thus, if your program includes CTYPE.H and then calls toupper,
the compiler uses the toupper macro:
i n t a = 'm' ;
a = touppe r ( a ) ;
You can force the compiler to use the function version of a routine by enclosing
the routine's name in parentheses:
# i n c l u d e < c t y p e . h>
i n t a = 'm' ;
a = ( touppe r ) ( a ) ;
Because the name toupper is not immediately followed by a left parenthesis, the
compiler cannot interpret it as a macro name. It must use the toupper function.
12 Microsoft C Run-Time Library Reference
A second way to do this is to "undefine" the macro definition with the #undef
directive:
#i n c l u d e < c t y p e . h>
#undef toupper
# i n c l u d e < c ty p e .h>
i n t t o u p p e r ( i n t _c l ;
Since this function declaration appears after the macro definition in CTYPE.H, it
causes the compiler to use the toupper function.
When you use errno, perror, and strerror, remember that the value of errno re
flects the error value for the last call that set errno. To avoid confusion, you
should always test the return value to verify that an error actually occurred. Once
you detennine that an error has occurred, use errno or perror immediately.
Otherwise, the value of errno may be changed by intervening calls.
Library math routines set errno by calling the matherr or _matherrl library
routines, which are described in the reference section. If you wish to handle math
errors differently from these routines, you can write your own routine and name
The ferror library routine allows you to check for errors in stream input/output
operations. This routine checks if an error indicator has been set for a given
stream. Closing or rewinding the stream automatically clears the error indicator.
You can also reset the error indicator by calling the clearerr library routine.
The feof library routine tests for end-of-file on a given stream. An end-of-file
condition in low-level input and output can be detected with the eof routine or
when a read operation returns 0 as the number of bytes read.
The _grstatus library routine allows you to check for errors after calling certain
graphics library operations. See the reference page on the _grstatus function for
details.
14 Microsoft C Run-Time Library Reference
1. 7 Operating-System Considerations
The library routines listed in this section behave differently under different oper
ating system versions. For more information on an individual routine, see the de
scription of that routine in the reference section.
Routine Restrictions
locking These routines are effective only in OS/2 and in
sopen DOS versions 3.0 and later.
_fsopen
dosexterr The dosexterr routine provides error handling for
system call Ox59 (get extended error) in DOS ver
sions 3.0 and later.
dup The dup and dup2 routines can cause unexpected re
dup2 sults in DOS versions earlier than 3.0. If you use
dup or dup2 to create a duplicate file handle for
stdio, stdout, stderr, stdaux, or stdprn, calling the
close function with one handle causes errors in later
1/0 operations that use the other handle. This
anomaly does not occur in OS/2 or in DOS versions
3.0 and later.
exec . When using the exec and spawn families of func
spawn tions under DOS versions earlier than 3.0, the value
of the argO argument (or argv[O] to the child
process) is not available to the user; a null string
("") is stored in that position instead. In OS/2, the
argO argument contains the command name; in DOS
versions 3.0 and later, it contains the complete com
mand path.
Microsoft C defines global variables that indicate the version of the current oper
ating system. You can use these to determine the operating-system version in
which a program is executing. See Chapter 3, "Global Variables and Standard
Types," for more information.
Using C Library Routines 15
1. 8 Floating-Point Support
Microsoft math library routines require floating-point support to perfonn calcula
tions with real numbers (numbers that can contain fractions). This support can be
provided by the floating-point libraries that accompany your compiler software
or by an 8087, 80287, or 80387 coprocessor. The names of the functions that re
quire floating-point support are listed below:
acos · cos fmodl powI
acosl cosl fmsbintoieee sin
asin cosh _fpteset sinl
asinl coshi frexp sinh
atan dieeetomsbin frexpl sinhl
atanl diffiime gcvt sqrt
atan2 dmsbintoieee hypot sqrtl
atan21 ecvt hypotl status87
atof exp Idexp strtod
atold expI ldexpl _strtold
bessel fabs log tan
cabs fabsl logl tanl
cabsl fcvt loglO tanh
ceil fieeetomsbin loglOI tanhl
ceill floor modf
clear87 tloorl modtl
=control87 fmod pow
Note that the bessel routine does not correspond to a single function, but to
twelve functions namedjO, jl, jn, yO, yl, yn, JOI, JU, Jnl, JOI, Jll, and
JDI. Also note that the _clear87 and _control87 functions are not available with
the /FPa compiler option.
Also requiring floating-point support is the printf family of functions (cprintf,
fprintf, printf, sprintf, vfprintf, vprintf, and vsprintf). These functions require
support for floating-point input and output if used to print floating-point values.
The C compiler tries to detect whether floating-point v alues are used in a pro
gram so that supporting functions are loaded only if required. This behavior
saves a considerable amount of space for programs that do not require floating
point support.
When you use a floating-point type specifier in the fonnat string for a printf or
scanf call, make sure you specify floating-point values or pointers to floating
point values in the argument list. These must correspond to any floating-point
16 Microson C Run-Time Library Reference
type specifiers in the format string. The presence of floating-point arguments al
lows the compiler to detect that floating-point support code is required. If a
floating-point type specifier is used to print an integer argument, for example,
floating-point values will not be detected because the compiler does not actually
read the format string used in the printf and scanf functions. For instance, the fol
lowing program produces an error at run time:
ma i n ( ) / * T hi s e x a mp l e c a u s e s a n e r r o r * /
{
l on g f = 10L ;
p r i nt f(" %f " , f ) ;
}
In the preceding example, the functions for floating-point support are not loaded
·
because
Fl oa t i n g p o i n t not l oa ded
Here is a corrected version of the above call to printf in which the long integer
value is cast to double:
ma i n( ) / * T h i s e x a mp l e w o r ks c o r r e c t l y * /
{
l ong f = 10L ;
p r i n t f (" % f " , (d o u b l e ) f } ;
}
With this set of functions, you can read from, write to, search, sort, copy, initial
ize, compare, or dynamically allocate and free _huge arrays; the _huge array can
be passed without difficulty to any of these functions in a compact-, large-, or
huge-model program. The model-independent routines in the above list (those
beginning with _f) are available in all memory models.
The memset, memcpy, and memcmp library routines are available in two ver
sions: as C functions and as intrinsic (in-line) code. The function versions of
these routines support huge pointers in compact and large memory models, but
the intrinsic versions do not support huge pointers. (The function version of such
routines generates a call to a library function, whereas the intrinsic version in
serts in-line code into your program. Your compiler documentation explains how
to select the intrinsic versions of library routines.)
CHAPTER
Run-Time Routines
by Category
Microsoft C library routines handle various kinds of tasks. If you know the type
of task you need done, but don't know exactly which routine to use, the catego
rized lists of routines in this chapter can help.
The descriptions here are intended only to give you a brief overview of the capa
bilities of the run-time library. For a complete description of the behavior, syn
tax, and use of each routine, see Part 2, "Run-Time Functions."
The main categories of library routines are
• Buffer manipulation
• Character classification and conversion
• Data conversion
• Directory control
• File handling
• Graphics
• Input and output
• Internationalization
• Math
• Memory allocation
• Process and environment control
• Searching and sorting
• String manipulation
• System calls
• Time
• Variable-length argument lists
19
20 Microsoft C Run-Time Library Reference
2. 1 Buffer Manipulation
The buffer-manipulation routines are useful for working with areas of memory
on a character-by-character basis. A "buffer" is an array of characters, similar
to a character string. However, unlike strings, buffers are not usually termi
nated with a null character ( '\0 ' ) . Therefore, the buffer-manipulation routines
always take a length or count argument. Function declarations for the buffer
manipulation routines are given in the include files MEMORY.H and
STRING.H, with an exception being the swab function, which appears in
STDLIB.H.
Routines beginning with _f are model independent; the _f stands for far. These
routines are useful in writing mixed-model programs because they can be called
from any program, regardless of the memory model being used.
Routine Use
memccpy, Copy characters from one buffer to another until a
_fmemccpy given character or a given number of characters has
been copied
memchr, _fmemchr Return a pointer to the first occurrence, within a
specified number of characters, of a given character
in the buffer
memcmp, _fmemcmp Compare a specified number of characters from two
buffers
memcpy, _fmemcpy Copy a specified number of characters from one
buffer to another
memicmp, Compare a specified number of characters from two
_fmemicmp buffers without regard to the case of the letters (up
percase and lowercase treated as equivalent)
memmove, Copy a specified number of characters from one
fmemmove buffer to another
rnemset, frnemset Use a given character to initialize a specified num
ber of bytes in the buffer
swab Swaps bytes of data and stores them at the specified
location
Run-Time Routines by Category 21
When the source and target areas overlap, only the memmove and _fmemmove
. functions are guaranteed to copy the full source properly. (The memcpy and
_fmemcpy routines do not always copy the full source in such cases.)
Routine Use
isalnum Tests for alphanumeric character
isalpha Tests for alphabetic character
isascii Tests for ASCII character
iscntrl Tests for control character
isdigit Tests for decimal digit
isgraph Tests for printable character except space
islower Tests for lowercase character
isprint Tests for printable character
ispunct Tests for punctuation character
isspace Tests for white-space character
isupper Tests for uppercase character
isxdigit Tests for hexadecimal digit
toascii Converts character to ASCII code
tolower Tests character and converts to lowercase if
uppercase
_tolower Converts character to lowercase (unconditional)
toupper Tests character and converts to uppercase if
lowercase
_toupper Converts character to uppercase (unconditional)
22 Microsoft C Run- Time Library Reference
All of these routines are implemented in two versions: as functions and as mac
ros. The function prototypes and macro definitions appear in CTYPE.H. Section
1 .4, "Choosing Between Functions and Macros," explains how to choose the
appropriate version. The toupper and tolower functions are also declared in the
STDLIB.H header file.
Routine Use
abs Finds absolute value of integer
atof Converts string to float
atoi Converts string to int
atol Converts string to long
atold Converts string to long double
ecvt Converts double to string
fcvt Converts double to string
gcvt Converts double to string
itoa Converts int to string
labs Finds absolute value of long integer
ltoa Converts long to string
strtod Converts string to double
Run-Time Routines by Category 23
2. 4 Directory Control
The directory-control routines let a program access, modify, and obtain informa
tion about the directory structure. These routines are functions and are declared
in DIRECT.H.
Routine Use
chdir Changes current working directory
_chdrive Changes current drive
getcwd Gets current working directory
__getdcwd Gets current working directory for the specified drive
__getdrive Gets the current disk drive
mkdir Makes a new directory
rmdir Removes a directory
_searchenv Searches for a given file on specified paths
2. 5 File Handling
The file-handling routines let you create, manipulate, and delete files. They also
set and check file-access permissions.
File-handling routines work on a file designated by a path name or by a "file
handle," an integer assigned by the operating system that identifies an open file.
These routines modify or give information about the designated file. Most of
them are declared in the include file 10.H, with the exceptions being the fstat
and stat functions (declared in SYS\STAT.H), the _fullpath routine (declared in
DIRECT.H), and the remove and rename functions (also declared in STDIO.H).
24 Microsoft C Run-Time Library Reference
Routine Use
access Checks file-permission setting
chmod Changes file-permission setting
chsize Changes file size
filelength Gets file length
fstat Gets file-status information on handle
_fullpath Makes an absolute path name from a relative
path name
isatty Checks for character device
locking Locks areas of file (available with OS/2 and
DOS versions 3.0 and later)
_makepath Merges path-name components into a single, full
path name
mktemp Creates unique file name
remove Deletes file
rename Renames file
setmode Sets file-translation mode
_splitpath Splits a path name into component pieces
stat Gets file-status information on named file
umask Sets default-permission mask
unlink Deletes file
2. 6 Graphics
Microsoft C graphics routines offer a wide variety of graphics functions, low
level graphics primitives, font functions, and presentation graphics (displays such
as graphs and pie charts).
Graphics functions are supplied in two libraries that must be explicitly linked
with your program. The GRAPIIlCS.LIB library provides support for low-level
graphics and character-font routines. The library PGCHART.LIB supports
presentation-graphics routines.
Category Task
Configuring mode and Select the proper display mode for the hardware and
environment (OS/2 establish memory areas for writing and displaying of
.
and DOS) images
Setting coordinates Specify the logical origin and the active display area
within the screen
Setting low-level Specify a palette mapping for low-level graphics
graphics palettes routines
Setting attributes Specify background and foreground colors, fill
masks, and line styles for low-level graphics routines
Creating graphics Draw and fill figures
output
Creating text output Write text on the screen
(OS/2 and DOS)
Transferring images Store images in memory and retrieve them
Displaying fonts Display text in character fonts compatible with
Microsoft Windows™
Routine Use
clearscreen Erases the screen and fills it with the current back
ground color
_getactivepage Gets the current active page number
_getbkcolor Returns the current background color
_getvideoconfig Obtains status of current graphics environment
_getvisualpage Gets the current visual page number
_grstatus Returns the status of the most recent graphics func
tion call
_setactivepage Sets memory area for the active page for writing
images
_setbkcolor Sets the current background color
settextrows Sets the number of text rows
_setvideomode Selects an operating mode for the display screen
setvideomoderows Sets the video mode and the number of rows for text
operations
_setvisualpage Sets memory area for the current visual page
The functions in this category establish window and view coordinate systems and
translate between physical, view, and window coordinate systems.
Routine Use
_getcurrentposition Determines current position in view coordinates
The default view coordinate system is identical to the physical screen coordinate
system. The physical origin (0, 0) is always in the upper-left corner of the dis
play. The x axis extends in the positive direction left to right, while the y axis ex
tends in the positive direction top to bottom.
The physical horizontal and vertical dimensions depend on the hardware display
configuration and the selected mode. These values are accessible at run time by
examining the numxpixels and numypixels fields of the videoconfig structure
returned by _getvideoconfig. (The _getvideoconfig routine is listed in the pre
vious section.)
The _setvieworg function allows you to move the viewport origin to a new posi
tion relative to the physical screen.
Routines that refer to coordinates on the physical screen or viewport require in
teger values. However, in real-world graphing applications, you might wish to
use floating-point values, such as stock prices or average rainfall. The window
coordinate system allows you to display graphics using floating-point values in
stead of integers.
The _setcliprgn function defines a restricted active display area on the screen.
The _setviewport function does the same thing and also resets the viewport
origin to the upper-left corner of the restricted active display area.
The view coordinates of any window coordinate can be determined with the
_getviewcoord_w and _getviewcoord_wxy functions. The window coordinates
of any view coordinate can be determined with the _getwindowcoord function.
Routine Use
_remapallpalette Changes all color indexes in the current palette
Some video modes support a "color palette," which is a table of the color values
that can be displayed together on the screen at any given time. A "color value" is
a long integer representing a color that can be displayed on your system.
In CGA color graphics modes, you can use the _selectpalette routine to choose
one of several predefined palettes.
On EGA and VGA video systems, you can "remap" (change) the palette using
the _remappalette or _remapallpalette routines. For instance, the EGA
ERESCOLOR mode offers a total of 64 color values, of which 1 6 can be dis
played at a time. In this mode, the palette contains 16 "color indices," or slots to
which you can assign color values.
graphics functions rely on a set of attributes that are set independently by the fol
lowing functions:
Routine Use
The _getcolor and _setcolor functions get or set the current color index for
graphics and font output. The _getbkcolor and _setbkcolor functions get or set
the current background color.
The _getfillmask and _setfillmask functions get or set the current fill mask. The
mask is an 8-by-8-bit template array, with each bit representing a pixel. If a bit is
0, the pixel in memory is left untouched, as the mask is transparent to that pixel.
If a bit is I , the pixel is assigned the current color value. The template is repeated
as necessary over the entire fill area.
The _getlinestyle and _setlinestyle functions get or set the current line style. The
line style is determined by a 1 6-bit template buffer with each bit corresponding
to a pixel. If a bit is 1 , the pixel is set to the current color. If a bit is 0, the pixel is
not changed. The template is repeated for the length of the line.
The _getwritemode and _setwritemode functions get or set the logical write
mode for straight line drawing. The default mode, _GPSET, causes lines to be
drawn in the current graphics color. Other modes combine the current graphics
color and the original screen image using various logical operations.
The name of each function announces its task or the figure it draws, as the follow
ing list indicates:
Routine Use
_rectangle, _rectangle_w,
_rectangle_wxy
Draw L scan-fill a rectangle
Most of these routines are available in several forms, which are indicated by their
names. Output functions without a suffix use the view coordinate system. Func
tions that end with _w take double values as arguments and use the window
coordinate system. Functions that end with wxy use _wxycoord structures to de
_
Circular figures, such as arcs and ellipses, are centered within a "bounding rec
tangle" specified by two points that define the diagonally opposed comers of the
rectangle. The center of the rectangle becomes the center of the figure, and the
rectangle' s borders determine the size of the figure.
All of the routines listed in this section work in OS/2 as well as DOS.
Routine Use
The _outtext and _outmem routines provide no formatting. If you want to out
put integer or floating-point values, you must convert the values into a string vari
able (using the sprintf function) before calling these routines.
The _outtext routine recognizes the \n (newline character) and \r (carriage re
turn) sequences. The _outmem routine treats these sequences as printable
graphics characters.
2. 6. 1. 7 Transferring Images
The functions in this category transfer screen images between memory and the
display, using a buffer allocated by the application, or determine the size in bytes
of the buffer needed to store a given image.
The functions that end with _w or _wxy use window coordinates; the other func
tions in this set use view coordinates.
32 Microsoft C Run-Time Library Reference
Routine Use
In some cases, the buffer needed to store an image with the _getimage functions
must be larger than 64K (65,535) bytes. Use the halloc routine to allocate a buff
er larger than 64K.
2. 6. 1. B Displaying Fonts
The functions listed in this section control the display of font-based characters on
the screen.
Routine Use
Category Task
Displaying presen Initialize video structures for presentation graphics
tation graphics and establishes the default chart type. Display
presentation-graphics chart: bar, column, pie, scat
ter, or line chart.
Analyzing Analyze data (does not display chart).
presentation-graphics
data
Routine Use
_pg_chart Displays a single-series bar, column, or line chart
_pg_chartms Displays a multiseries bar, column, or line chart
_pg_chartpie Displays a pie chart
_pg_chartscatter Displays a scatter diagram for a single series of data
_pg_chartscatterms Displays a scatter diagram for more than one series
of data
_pg_defaultchart Initializes all necessary variables in the chart en
vironment for a specified chart type
_pg_initchart Initializes the presentation-graphics library
34 Microsoft C Run·Time Library Reference
Routine Use
_pg_analyzechart Analyzes a single series of data for a bar, column, or
line chart
Routine Use
_pg_hlabelchart Writes text horizontally on the screen
_pg_vlabelchart Writes text vertically on the screen
_pg_getpalette Retrieves current colors, line styles, fill patterns, and
plot characters for all presentation-graphics palettes
_pg_setpalette Sets current colors, line styles, fill patterns, and plot
characters for all presentation-graphics palettes
_pg_resetpalette Sets current colors, line styles, fill patterns, and plot
characters to the default values for the current screen
mode
I. Stream
2. Low-level
The "console and port" 1/0 routines allow you to read or write directly to a con
sole (keyboard and screen) or an I/O port (such as a printer port). The port 1/0
routines simply read and write data in bytes. With console 1/0 routines, some ad
ditional options are available, such as detecting whether a character has been
typed at the console. YOU c an also choose between echoing characters to the
screen as they are read or reading characters without echoing.
The C library also provides a number of direct DOS 1/0 system call routines.
These are described in Section 2. 14, "System Calls."
File 1/0 operations can be performed in two modes: text or binary. The following
section describes these modes and their use.
WARNING Because stream routines are buffered and low-level routines are not, the two
types of routines are generally incompatible. You should use either stream or low-level
routines consistently forprocessing a given file.
Sometimes you may want to process a file without making those translations. In
these cases you use binary mode, which suppresses CR-LF translations.
You can control the file translation mode in the following ways:
• To process a few selected files in binary mode, while retaining the default
text mode for most files, you can specify binary mode when you open the
selected files. The fopen routine opens a file in binary mode when you
specify the letter b in the access-mode string for the file. The open routine
opens a file in binary mode when you specify the 0_BINARY flag in the of/ag
argument. For more information about fopen and open, see the reference de
scription of each routine.
• To process most or all files in binary mode, you can change the default mode
to binary. The global variable _fmode controls the default translation mode,
which is normally text. If you set _fmode to O_BINARY, the default mode is
binary except for stdaux and stdprn, which are opened in binary mode by
default.
1. Link with the file BINMODE.OBJ (supplied with Microsoft C). This changes
the initial setting of _fmode to the 0_BINARY flag, causing all files except
stdio, stdout, and stderr to be opened in binary mode.
2. Change the value of _fmode directly by setting it to the 0_BINARY flag in
your program. This has the same effect as linking with BINMODE.OBJ.
You can still override the default mode (now binary) for a particular file by open
ing it in text mode. Specify the letter t when using fopen, or specify the 0_TEXT
flag when using open.
By default, the stdio, stdout, and stderr files are opened in text mode, and the
stdaux and stdprn files are opened in binary mode. The setmode routine allows
you to change these defaults or change the mode of a file after it has been
opened. See the reference description of setmode for details.
When a file is opened for 1/0 using the stream functions, the opened file is as
sociated with a structure of type FILE (defined in STDIO.H) containing basic in
formation about the file. A pointer to the FILE structure is returned when the
stream is opened. Subsequent operations use this pointer (also called the "stream
pointer," or just "stream") to refer to the file.
The stream functions provide for buffered, formatted, or unformatted input and
output. When a stream is buffered, data that is read from or written to the stream
is <;:ollected in an intermediate storage location called a "buffer". In write opera
tions, the output buffer's contents are written to the appropriate final location
when the buffer is full, the stream is closed, or the program terminates normally.
The buffer is said to be "flushed" when this occurs. In read operations, a block of
data is placed in the input buffer read from the buffer; when the input buffer is
empty, the next block of data is transferred into the buffer.
B uffering produces efficient 1/0 because the system can transfer a large block of
data in a single operation rather than performing an 1/0 operation each time a
data item is read from or written to a stream. However, if a program terminates
abnormally, output buffers may not be flushed, resulting in loss of data.
Routine Use
clearerr Clears the error indicator for a stream
The fdopen, fopen, freopen, and _fsopen functions return a FILE pointer. You
normally assign the pointer value to a variable and use the variable to refer to the
opened stream. For instance, if your program contains the lines
FI L E *i n fil e
i n fi l e= fopen ( " test . da t " , "r" ) ;
you can use the FILE pointer variable i nfi 1 e to refer to the stream.
You can refer to the standard streams with the following predefined stream
pointers:
40 Microsoft C Run-Time Library Reference
Pointer Stream
stdin Standard input
You can use these pointers in any function that requires a stream pointer as an ar
gument. Some functions, such as getchar and putchar, are designed to use stdio
or stdout automatically. The pointers stdio, stdout, stderr, stdaux, and stdprn
are constants, not variables; do not try to assign them a new stream pointer value.
DOS and OS/2 allow you to redirect a program' s standard input and standard out
put at the operating-system command level. OS/2 also allows you to redirect a
program's standard error. See your operating system user's manual for a com
plete discussion of redirection.
Within your program, you can use freopen to redirect stdio, stdout, stderr,
stdaux, or stdprn so that it refers to a disk file or to a device. See the reference
description of freopen for more details.
By using the setbuf or setvbuf function, you can cause a stream to be unbuff
ered, or you can associate a buffer with an unbuffered stream. Buffers allocated
by the system are not accessible to you, but buffers allocated with setbuf or
setvbuf refer to arrays in your program and can be manipulated. Buffers can be
any size up to 32,767 bytes. This size is set by the manifest constant BUFSIZ in
STDIO.ff if you use seftbuf; if you use setvbuf, you can set the size of the buffer
yourself. (See the descriptions of setbuf and setvbuf in the reference section for
more details.)
NOTE These routines affect only buffers created by C library routines. They have no effect
on buffers created by the operating system.
Run· Time Routines by category 41
Reading and writing operations on streams always begin at the current position
of the stream, known as the "file pointer" for the stream. The file pointer is
changed to reflect the new position after a read or write operation takes place.
For example, if you read a single character from a stream, the file pointer is in
creased by one byte so that the next operation begins with the first unread char
acter. If a stream is opened for appending, the file pointer is automatically
positioned at the end of the file before each write operation.
The fseek and fsetpos functions allow you to position the file pointer anywhere
in a file. The next operation occurs at the positi on you specified. The rewind
routine positions the file pointer at the beginning of the file. Use the ftell or
fgetpos routine to determine the current position of the file pointer.
The feof macro detects an end-of-file condition on a stream. Once the end-of-file
indicator is set, it remains set until the file is closed, or until clearerr, fseek,
fsetpos, or rewind is called.
Streams associated with a character-oPiented device (such as a console) do not
have file pointers. Data coming from or going to a console cannot be accessed
randomly. Routines that set or get the file-pointer position (such as fseek,
fgetpos, fsetpos, ftell, or rewind) have undefined results if used on a stream as
sociated with a character-oriented device.
2. 7. 3 Low-Level Routines
Low-level input and output calls do not buffer or fonnat data. Declarations
for the low-level functions are given in the include files IO.H, FCNTL.H,
SYS\TYPES.H, and SYS\STAT.H. Unlike the stream functions, low-level func
tions do not require the include file STDIO.H. However, some common con
stants are defined in STDIO.H; for example, the end-of-file indicator (EOF) may
be useful. If your program requires these constants, you must include STDIO.H.
Routine Use
close Closes a file
creat Creates a file
dup Creates a second handle for a file
dup2 Reassigns a handle to a file
eof Tests for end-of-file
lseek Repositions file pointer to a given location
open Opens a file
read Reads data from a file
sopen Opens a file for file sharing
tell Gets current file-pointer position
umask Sets default file-pennission mask
write Writes data to a file
Stream Handle
stdin 0
stdout 1
stderr 2
stdaux (DOS only) 3
stdprn (DOS only) 4
You can use these file hanqles without previously opening the files. The files are
opened and the handles are assigned when the program starts.
The dup and dup2 functions allow you to assign multiple handles for the same
file. These functions are typically used to associate the predefined file handles
with different files.
44 Microsoft C Run-Time Library Reference
In DOS and OS/2, you can redirect the standard input and standard output at the
operating-system command level. OS/2 also allows you to redirect the standard
error. See your operating system user's manual for a complete discussion of
redirection.
Routine Use
cgets Reads a string from the console
cprintf Writes formatted data to the console
NOTE Programs that need only run under DOS can also use a number of direct DOS 110
system calls ( _das_ open, _das_read, das close, etc.) These are described in detail In
_ _
The console or port does not have to be opened or closed before 1/0 is per
formed, so there are no open or close routines in this category. The port 1/0
Run-Time Routines by Category 45
routines inp and outp read or write one byte at a time from the specified port.
The inpw and outpw routines read and write two-byte words, respectively.
The console 1/0 routines allow reading and writing of strings (cgets and cputs),
formatted data (cscanf and cprintf), and characters. Several options are available
when reading and writing characters.
The putch routine writes a single character to the console. The getch and getche
routines read a single character from the console; getche echoes the character
back to the console, while getch does not. The ungetch routine "ungets" the last
character read; the next read operation on the console begins with the "ungotten"
character.
The kbhit routine determines whether a key has been struck at the console. This
routine allows you to test for keyboard input before you attempt to read from the
console.
NOTE The console 110 routines are not compatible with stream or low-level library
routines and should not be used with them.
2. 8 Internationalization
Internationalization routines are useful for creating different versions of a pro
gram for international markets. These routines are declared in the header file
LOCALE.H, except for strftime, which is declared in TIME.H.
Routine Use
localeconv Sets a structure with appropriate values for format
ting numeric quantities
setlocale Selects the appropriate locale for the program
strcoll Compares strings using locale-specific information
strftime Formats a date and time string
strxfrm Transforms a string based on locale-specific
information
2. 9 Math
The math routines allow you to perform common mathematical calculations. All
math routines work with floating-point values and therefore require floating
point support (see Section 1 .8, "Floating-Point Support").
46 Microsoft C Run-Time Library Reference
The math library provides two versions of some routines. The first version of the
routine supports double arguments and return values. The second version sup
ports an 80-bit data type, allowing the routine to take long double arguments and
return a long double value. The second version usually has the same name with
the suffix I. For instance, the acos routine supports double arguments and return
values, while acosl supports long double arguments and return values.
Routines which support long double values are not available when you compile
with the /Fpa (alternate math) compiler option. The same is true of the _clear 87,
_control87, and _status87 routines.
Most math declarations are in the include file MATH.H. However, the clear87,
_control87, _fpreset, and _status87 routines are defined in FLOAT.H:-the abs
and labs functions are defined in MATH.H and STDLIB.H, and the div and ldiv
routines are declared in STDLIB.H.
Routine Use
acos, acosl Calculate the arccosine
asin, asinl Calculate the arcsine
atan, atanl Calculate the arctangent
�tan2, atan21 Calculate the arctangent
bessel Calculates Bessel functions
cabs, cabsl Find the absolute value of a complex number
ceil, ceill Find the integer ceiling
_clear87 Gets and clears the floating-point status word
control87 Gets the old floating-point control word and sets a
new control-word value
cos, cosl Calculate the cosine
cosh, coshl Calculate the hyperbolic cosine
dieeetomsbin Converts IEEE double-precision number to Micro
soft (MS) binary format
div Divides one integer by another, returning the
quotient and remainder
dmsbintoieee Converts Microsoft binary double-precision number
to IEEE format
exp, expl Calculate the exponential function
fabs, fabsl Find the absolute value
Run-Time Routines by Category 47
floor, floorl Find the largest integer less than or equal to the
argument
_Irotl, _Irotr Shift an unsigned long int item left ( _lrotl) or right
( _lrotr)
modf, modfl Break down the argument into integer and fractional
parts
The be�el routine does not correspond to a single function, but to twelve func
tions named jO, jl, jn, yO, yl, yn, JOI, jll, jnl, JOI, Jll, and Jnl .
The matherr and _matherrl routines are invoked by the math functions when er
rors occur. The matherr routine handles functions that return a double value and
_matherrl handles routines that return a long double.
These routines are defined in the library, but you can redefine them for different
error-handling. The user-defined function, if given, must follow the rules given
in the reference description of matherr and �matherrl.
You are not required to supply a definition for the matherr routines. If no defini
tion is present, the default error returns for each routine are used. The reference
description of each routine describes that routine's error returns.
2. 10 Memory Allocation
The memory-allocation routines allow you to allocate, free, and reallocate blocks
of memory. Memory-allocation routines are declared in the include file
MALLOC.H.
Routine Use
alloca Allocates a block of memory from
the program's stack
_nmalloe
malloc, bmalloc, -fmalloc, Allocate a block of memory
_nrealloe
realloc, brealloc, -frealloc, Reallocate a block to a new size
The malloc and free routines allocate and free memory space, respectively,
while a program runs. The malloc routine allocates memory from the "heap,"
which is a pool of memory not otherwise used by your program. In tiny-, small-,
and medium-model programs, the heap consists of unused memory in your pro
gram's default data segment. In compact-, large-, and huge-model programs, it is
unused memory outside the default data segment.
The malloc and free routines satisfy the memory-allocation requirements of most
programs. More specialized memory-management routines are discussed below.
The realloc and _expand routines can expand or shrink an allocated memory
block. They behave differently in cases in which there is not enough room to ex
pand the block in its current location. In this case, realloc moves the block as
needed, but _expand does not.
The calloc routine allocates memory for an array and initializes every byte in the
allocated block to 0.
The halloc routine is similar to calloc, except that it can allocate memory for a
huge array (one that exceeds 64K in size). This routine is useful when you need a
50 Microsoft C Run-Time Library Reference
very large data object, or if you need to return allocated memory to the operating
system for subsequent calls to the spawn family of functions.
• Localized data. Based heaps allow you to group related data in a single seg
ment. This can simplify the management of related data. In OS/2, based heaps
can also minimize the risk of general protection faults and improve
performance.
• Faster pointer arithmetic. Although the based heap lies in the far data seg
ment, pointers to its data items are the same size as near pointers. Thus,
pointer arithmetic on items in a based heap is faster than pointer arithmetic on
items in the far heap.
The _bheapseg routine allocates a based heap segment, from which you can then
allocate blocks of memory. You can call _bheapseg more than once to allocate
Run-Time Routines by Category 51
The _bfreeseg routine frees a based-heap segment. This routine frees every block
in the based-heap segment, whether or not you previously freed the blocks
individually.
NOTE Near- . far- . and based-heap calls are not ANSI compatible and will make your pro
gram less portable.
All process-control functions except signal are declared in the include file
PROCESS.H. The signal function is declared in SIGNAL.H. The abort, exit,
and system functions are also declared in the STDLIB.H include file. The
environment-control routines (getenv and putenv) are declared in STDLIB.H.
Routine Use
The atexit and onexit routines create a list of functions to be executed when the
calling program terminates. The only difference between the two is that atexit is
part of the ANSI standard. The onexit function is offered for compatibility with
previous versions of Microsoft C.
The _exit routine terminates a process immediately, whereas exit terminates the
process only after flushing buffers and calling any functions previously regis
tered by atexit and onexit. The _cexit and _c_exit routines are identical to exit
and _exit, respectively, except that they return control to the calling program
without terminating the process.
The setjmp and longjmp routines save and restore a stack environment. These
allow you to execute a nonlocal goto.
The exec and spawn routines start a new process called the "child" process. The
difference between the exec and spawn routines is that the spawn routines are
capable of returning control from the child process to its caller (the "parent"
process). Both the parent process and the child process are present in memory
(unless P_OVERLAY is specified). In the exec routines, the child process over
lays the parent process, so returning control to the parent process is impossible
(unless an error occurs when attempting to start execution of the child process).
54 Microsott C Run·Time Library Reference
There are eight fonns each of the spawn and exec routines (see Table 2. 1 ). The
differences among the fonns involve the method of locating the file to be ex
ecuted as the child process, the method for passing arguments to the child
process, and the method of setting the environment.
Passing an argument list means that the arguments to the child process are listed
separately in the exec or spawn call. Passing an argument array means that the ar
guments are stored in an array, and a pointer to the array is passed to the child
process. The argument-list method is typically used when the number of argu
ments is constant or is known at compile time. The argument-array method is use
ful when the number of arguments must be detennined at run time.
Argument-Passing
Routines Locating the File Convention Environment Settings
execl, spawnl Do not use PATH Argument list Inherited from parent
execv, spawnv Do not use PATH Argument array Inherited from parent
The assert macro is typically used to test for logic errors. It prints a message
when a given "assertion" fails to hold true. Defining the identifier NDEBUG to
any value causes occurrences of assert to be removed from the source file, thus
allowing you to tum off assertion checking without modifying the source file.
Routine Use
bsearch Perfonns binary search
lfmd Perfonns linear search for given value
lsearch Perfonns linear search for given value, which is
added to array if not found
qsort Perfonns quick sort
2. 13 String Manipulation
The string functions are declared in the include file STRING.H. They allow you
to compare strings, copy them, search for strings and characters, and perfonn
various other operations.
Routine Use
strcat, _fstrcat Append one string to another
strchr, _fstrchr Find first occurrence of a given character in a string
strcmp, _fstrcmp Compare two strings
strcpy, _fstrcpy Copy one string to another
strcspn, _fstrcspn Find first occurrence of a character from a given
character set in a string
strdup, _fstrdup, Duplicate a string
_nstrdup
strerror Maps an error number to a message string
56 Microsoft C Run· Time Library Reference
2. 14 System Calls
The following routines give access to IBM-PC BIOS interrupts and DOS system
calls. Except for the FP_OFF, FP_SEG, and segread routines, these routines are
for DOS application programs only; they do not work under OS/2.
Run-Time Routines by Category 57
Routine Use
_bios_disk Issues service requests for both hard and floppy
disks, using INT Ox 1 3
_bios_equiplist Performs an equipment check, using INT Ox 1 1
_bios_keybrd Provides access to keyboard services, using
INT Ox l 6
_bios_memsize Obtains information about available memory, using
INT 0x l 2
_bios_printer Performs printer output services, using INT Ox 17
_bios_serialcom Performs serial communications tasks, using
INT Ox l 4
NOTE BIOS routines are hardware dependent. Some of them may not work as expected
on machines whose hardware differs from the IBM PC.
2. 14.2 D OS Interface
These routines are implemented as functions and declared in DOS.H.
Routine Use
bdos Invokes DOS system call; uses only DX and AL
registers
_chain_intr Chains one interrupt handler to another
_disable Disables interrupts
_dos_allocmem Allocates a block of memory, using DOS system
call Ox48
_dos_close Closes a file, using DOS system call Ox3E
dos creat Creates a new file and erases any existing file
having the same name, using DOS system call Ox3C
58 Microsoft C Run-Time Library Reference
dos tindfirst Finds first occurrence of a given file, using DOS sys
tem call Ox4E
_dos_getdate Gets the system date, using DOS system call Ox2A
_dos_getftime Gets the date and time a file was last written, using
DOS system call Ox57
dos setfileattr Sets the current attributes of a file, using DOS sys
tem call Ox43
_dos_setftime Sets the date and time that the specified file was last
written, using DOS system call Ox57
Run-Time Routines by Category 59
_dos_settime Sets the system time, using DOS system call Ox2D
The dosexterr function obtains and stores the error information returned by DOS
system call Ox59 (extended error handling). This function is provided for use
w ith DOS versions 3.0 and later.
The bdos routine is useful for invoking DOS calls that use either or both of the
DX (DH/DL) and AL registers for arguments. However, bdos should not be used
to invoke system calls that return an error code in AX if the cany flag is set;
since your program cannot detect whether the cany flag is set, it cannot deter
mine whether the value in AX is a legitimate value or an error value. In this case,
the intdos routine should be used instead, since it allows the program to detect
whether the carry flag is set. The intdos routine can also be used to invoke DOS
calls that use registers other than DX and AL.
60 Microsoft C Run· Time Libraty Reference
The intdosx routine is similar to the intdos routine, but is used when ES is re
quired by the system call, when DS must contain a value other than the default
data segment (for instance, when a far pointer is used), or when making the sys
tem call in a large-model program. When calling intdosx, give an argument that
specifies the segment values to be used in the call.
The int86 routine can be used to invoke any interrupt. The int86x routine is simi
lar; however, like the intdosx routine, it is designed to work with large-model
programs and far items, as described in the preceding paragraph.
The FP_OFF and FP_SEG routines allow easy access to the segment and offset
portions of a far pointer value. FP_OFF and FP_SEG are implemented as macros
and defined in DOS.H. You can use these macros in OS/2 as well as DOS.
The segread routine returns the current values of the segment registers. This
routine is typically used with the intdosx and int86x routines to obtain the cor
rect segment values.
The _chain_intr routine is useful for chaining interrupt handlers together. The
_enable routine enables interrupts, while the _disable routine disables interrupts.
The routines prefixed with _dos_ are all direct system interfaces that use the sys
tem calls noted above. More detailed information on these system calls can be
found in the MS-DOS Encyclopedia (Duncan, ed.; Redmond, WA: Microsoft
Press, 1 988)or the Programmer's PC Sourcebook (Hogan; Redmond, WA:
Microsoft Press, 1 988).
NOTE The DOS interface 110 routines are generally Incompatible with console, low-level,
and stream 110 routines. Do not mix different types of 110 routines in the same source file.
2. 15 Time
The time functions allow you to obtain the current time, then convert and store it
according to your particular needs. The current time is always taken from the sys
tem time.
Routine Use
asctime Converts time from type struct tm to a character
string
clock Returns the elapsed CPU time for a process
ctime Converts time from a long integer to a character
string
Run· Time Routines by Category 61
The time and ftime functions return the current time as the number of seconds
elapsed since midnight Universal Coordinated Time (UTC) on January 1 , 1 970.
This value can be converted, adjusted, and stored in a variety of ways by using
the asctime, ctime, gmtime, localtime, and mktime functions. The utime func
tion sets the modification time for a specified file, using either the current time or
a time value stored in a structure.
The clock function returns the elapsed CPU time for the calling process.
The ftime function requires two files: SYS\TYPES.H and SYS\TIMEB.H. It is
declared in SYS\TIMEB.H. The utime function also requires two include files:
SYS\TYPES.H and SYS\UTIME.H. It is declared in SYS\UTIME.H. The re
mainder of the time functions are declared in the include file TIME.ff.
When you want to use ftime or localtime to make adjustments for local time,
you must define an environment .variable named TZ. Section 3.2, which de
scribes the global variables daylight, timezone, and tzname, includes a discus
sion of the TZ variable. TZ is also described on the tzset reference page in Part 2
of this book.
The _strdate and _strtime routines return strings containing the current date and
time, respectively, in the DOS and OS/2 date and time format rather than in the
XENIX-style formats.
The stfrtime function is useful for creating international versions of a program.
See Section 2.8, "Internationalization."
62 Microsoft C Run-Time Library Reference
Routine Use
va_arg Retrieves argument from list
For more information on the differences between the two versions and for an ex
planation of how to use the macros, see their descriptions in Part 2 of this book.
CHAPTER
Global Variables
and Standard Types
3. 1 _amblksiz
The _amblksiz variable controls memory heap granularity.
The _amblksiz variable controls the amount of memory used in the heap for dy
namic memory allocation.
Memory space is always requested from the operating system in blocks contain
ing _amblksiz bytes. The first time a program calls a memory-allocation func
tion such as malloc, the operating system allocates a block of heap memory. The
size of this block is defined by _amblksiz, which has a default value of SK
(8, 192 bytes).
Later memory requests are satisfied from the original block. When that block is
exhausted, another block of _amblksiz bytes is allocated. If your C program
allocates a block larger than _amblksiz, multiple blocks that are each of size
_amblksiz are allocated until the request is satisfied.
To change the size of the default memory block, assign the desired size to the
_amblksiz variable, as in the following example:
ambl ks i z = 2048 ;
63
64 Microsoft C Run· Time Library Reference
The heap allocator always rounds the operating-system request to the nearest
power of 2 greater than or equal to _amblksiz. The above statement allocates
memory in multiples of 2K (2,048 bytes).
Fewer system calls are required if you set _amblksiz to a large value, but your
program may use more memory than needed. If program speed is important, set
_amblksiz to a large value. If size is important, set _amblksiz to a smaller value.
Note that adjusting the value of _amblksiz affects allocation in the near, far, and
based heaps. The value of _amblksiz has no effect on huge memory blocks
(those allocated with halloc and similar functions).
Some time and date routines use the daylight, timezone, and tzname variables
to make local-time adjustments. Whenever a program calls the ftime, localtime,
or tzset function, the value of daylight, timezone, and tzname is determined
from the value of the TZ environment variable. If you do not explicitly set the
value of TZ, the default value of PST8PDT is used. The following list shows
each variable and its value:
Variable Value
daylight Nonzero if a daylight-saving-time zone (DST) is
specified in TZ; otherwise zero. Default value is one.
These variables are declared in the STDLIB.H include file. Manifest constants
for the errno variables are declared in the ERRNO.H include file. The declara
tions are as follows:
extern int _doserrno;
The include file ERRNO.H contains the definitions of the errno values. How
ever, not all of the definitions given in ERRNO.H are used in DOS and OS/2.
Some of the values in ERRNO.H are present to maintain compatibility with
XENIX and UNIX operating systems.
The errno values in DOS and OS/2 are a subset of the values for errno in
XENIX systems. Thus, the errno value is not necessarily the same as the actual
error code returned by a DOS or OS/2 system call. To access the actual DOS and
OS/2 error code, use the _doserrno variable, which contains this value.
In general, you should use _doserrno only for error detection in operations in
volving input and output, since the errno values for input and output errors have
DOS and OS/2 error-code equivalents. In other cases, the value of _doserrno is
undefined.
The syserrlist variable is an array; the perror and strerror routines use it to
process error infonnation. The sys_nerr variable tells how many elements the
sys_errlist array contains.
66 Mit:roso" C Run-Time Library Reference
Table 3. 1 gives the errno values for DOS and OS/2, the system error message
for each value, and the value of each constant. Note that only the ERANGE and
EDOM constants are specified in the ANSI standard.
3. 4 _fmode
The fmode variable controls the default file-translation mode.
These variables are useful for creating programs that run in different versions of
DOS and OS/2. For example, you can test the _osmajor variable before making
a call to sopen; if the major version number is earlier (less) than 3, open should
be used instead of sopen.
The _osmode variable indicates whether the program is in OS/2 protected mode
or in real mode (DOS or OS/2 real mode). An osmode value of DOS MODE in
dicates real mode operation and a value of OS�MODE indicates protected
operation.
3. 6 environ
The environ variable is a pointer to the strings in the process environment.
The environ variable is an array of pointers to the strings that constitute the
process environment. The environment consists of one or more entries of
the form
NAME=string
where NAME is the name of an environment variable and string is the value of
that variable. The string may be empty. The initial environment settings are taken
from the o�rating-system environment at the time of program execution.
The getenv and putenv routines use the environ variable to access and modify
the environment table. When putenv is called to add or delete environment set
tings, the environment table changes size; its location in memory may also
change, depending on the program's memory requirements. The environ varia
ble is adjusted in these cases and always points to the correct table location.
3. 7 _psp
The _psp variable contains the segment address of the program segment prefix
(PSP) for the process.
It is declared in the STDLIB.H include file as follows:
extern unsigned int _psp;
The PSP contains execution information about the process, such as a copy of the
command line that invoked the process and the return address on process termina
tion or interrupt. The _psp variable can be used to form a long pointer to the
PSP, where _psp is the segment value and 0 is the offset value.
Note that the _psp variable is supported only in DOS.
3. 8 Standard Types
A number of library routines use values whose types are defined in include files.
In the following list, these types are described, and the include file defining each
type is given.
Run-Time
Functions
Run- Time Functions
The second part of this book is the reference section. It describes,
in alphabetical order, each function of the run-time library pro
vided with the Microsoft C Professional Development System.
Each reference entry gives syntax, return values, and other useful
information about the library functions. Information on compati
bility is supplied to assist you in writing portable programs.
75
to stderr, then calls raise(SIGABRT). The action taken in response to the SIGABRT signal
depends on what action has been defined for that signal in a prior call to the signal func
tion. The default SIGABRT action is for the calling process to terminate with exit code 3,
returning control to the parent process or operating system.
The abort function does not flush stream buffers or do atexit/onexit processing.
Return Value The abort function does not return control to the caller. Rather, it terminates the process
and, by default, returns an exit code of 3 to the parent process.
In multithread libraries, the abort function does not call raise(SIGABRT). Instead, it
simply terminates the process with exit code 3.
See Also exec functions, exit, _exit, raise, signal, spawn functions
I * A B O RT . C : T h i s t r i e s t o o p e n a f i l e a n d a b o r t s i f t h e a t t em p t f a i l s . * /
#i n c l u d e < s t d i o . h >
#i n c l u d e < s t d l i b . h >
77 abort
v o i d ma i n ( )
{
FI LE *st ream ;
el se
fcl o s e ( s t ream ) ;
Output
C o u l d n ' t o p e n f i l e : N o s u c h f i l e o r d i r e c t o ry
a b n o rm a l p r o g r a m t e rm i n a t i o n
abs 78
#include <Stdlib.h> Required only for function declarations; use either STDLIB.H
#include <math.h> or MATH.H
n Integer value
Remarks The abs function returns the absolute value of its integer argument 11.
Return Value The abs function returns the absolute value of its argument. There is no error return.
I * A B S . C : T h i s p r o g r a m c omp u t e s a n d d i s p l a y s t h e a b s o l u t e v a l u e s o f
* s e v e r a l n um b e r s .
*/
v o i d ma i n ( )
{
i nt ix = -4 , i y ;
l on g lx = - 4 1 567 L , l y ;
doubl e dx = - 3 . 1 4 1 5 9 3 , dy ;
iy = a bs ( i x ) ;
p r i n t f ( " T h e a bsol ute v a l ue of %d i s %d\ n " , i x ' i y ) ;
ly = l abs ( l x ) ;
p r i ntf ( " T h e a b s o l ute v a l ue of %l d i s %l d \ n " , 1 x ' l y ) ;
dy = fabs ( dx ) ;
p r i n t f ( " T h e a b s o l u t e v a l u e o f % f i s % f \ n " , d x , dy l ;
79 abs
Output
Remarks With files, the access function detennines whether the specified file exists and can be
accessed in mode. The possible mode values and their meanings in the access call are as
follows:
Value Meaning
()() Check for existence only
02 Check for write pennission
04 Check for read pennission
06 Check for read and write pennission
With directories, access detennines only whether the specified directory exists; under
DOS and OS/2, all directories have read and write access.
Return Value The access function returns the value 0 if the file has the given mode. A return value of -1
indicates that the named file does not exist or is not accessible in the given mode, and
errno is set to one of the following values:
Value Meaning
EACCES Access denied: the file's pennission setting does not allow the
specified access.
ENOENT File or path name not found.
81 access
#i n c l u d e < i o . h > .
#i n c l u d e < s t d i o . h >
#i n c l ude < s t d l i b . h>
v o i d ma i n ( )
(
I* Check for exi stence */
i f ( ( acces s < • a ccess . c • , 0 > > != -1 >
(
p r i n t f C " Fi l e ex i s t s \ n " ) ;
I * C h e c k f o r w r i t e p e rm i s s i o n * /
i f { ( a cces s ( " a ccess . c " , 2 ) ) ! = -1 )
p r i n t f ( " F i l e h a s w r i t e p e rm i s s i o n \ n " );
Output
Fi l e exi sts
F i l e h a s w r i t e p e rm i s s i o n
acos Functions 82
#include <math.h>
#include <errno.h> Required for definition of ermo constant
Rematts The acos functions return the arccosine of x in the range 0 to 1t radians. The value of x
must be between -1 and 1 . The acosl function is the 80-bit counterpart, which uses an 80-
bit, 1 0-byte coprocessor form of arguments and return values. See the reference page on
the long double functions for more details on this data type.
Return Value The acos functions return the arccosine result. If x is less than - 1 or greater than l , the
function sets ermo to EDOM, prints a DOMAIN error message to stderr, and returns 0.
Error handling can be modified with the matherr (or _matherrl) routine.
Compatibility acos
acosl
See Also asin functions, atan functions, cos functions, matherr, sin functions, tan functions
����-
Exampm ��
1 * A S I N C O S . C : T h i s p r o g r a m p r om p t s f o r a v a l u e i n t h e r a n g e - 1 t o 1 .
* I n p u t v a l u e s o u t s i d e t h i s r a n g e w i l l p r o d u c e D O MA I N e r r o r m e s s a g e s .
* I f a v a l i d v a l u e i s entered , t h e program p r i n t s t h e a rc s i n e a n d t h e
* a rc c o s i n e o f t h a t v a l u e .
*I
#i n c l u d e < ma t h . h >
#i n c l ude <stdi o . h>
#i n c l u d e <stdl i b . h>
#i n c l ude < e r rn o . h >
83 acos Functions
v o i d ma i n ( }
(
doubl e x , y ;
Output
E n t e r a r e a l n um b e r b e t w e e n - 1 a n d 1 : . 32696
A r c s i n e o f 0 . 3 2 6 9 6 0 = 0 . 3 3 3085
Arccos i ne of 0 . 326960 = 1 . 237 7 1 1
al/oca 84
Remarks The alloca routine allocates size bytes from the program's stack. The allocated space is
automatically freed when the calling function is exited.
When you compile with optimization on (either by default or by using one of the /0 op
tions), the stack pointer may not be restored properly in functions that have no local varia
bles and that also reference the alloca function. The following program demonstrates the
·
problem:
I * C o m p i l e wi t h C L / L p / AM / O x / Fe * /
# i n c l u d e <ma l l o c . h >
v o i d ma i n ( v o i d
(
f u n c ( 10 ) ;
To ensure that the stack pointer is properly restored, make sure that any function refer
encing alloca declares at least one local variable.
The pointer value returned by alloca should never be passed as an argument to free, nor
should alloca be used in an expression that is an argument to a function.
Return Value The alloca routine returns a void pointer to the allocated space, which is guaranteed to be
suitably aligned for storage of any type of object. To get a pointer to a type other than
char, use a type cast on the return value. The return value is NULL if the space cannot be
allocated.
85 alloca
I * A L LOCA . C : T h i s p r o g r a m c h e c k s t h e s t a c k s p a c e a v a i l a b l e before
* and a ft e r u s i n g t h e a l l oc a func t i on t o a l l o c a t e space on the s t a c k .
*I
#i n c l u d e <ma l l oc . h >
#i n c l u d e < s t d i o . h>
v o i d ma i n ( )
(
c h a r *buffe r :
I * A l l o c a t e memo ry f o r s t r i ng . * /
b u f f e r - a l l oc a C 1 2 0 * s i zeof ( c h a r > l :
p r i n t f ( " En t e r a s t r i n g : • l :
g et s ( buffer l :
p r i n t f ( " Y o u entered : % s \ n " , b u f f e r l :
p r i n t f ( " By t e s a va i l a b l e o n s ta c k : % u \ n " , s t a c k a v a i l C l l :
Output
Byt e s a v a i l a b l e o n s ta c k : 2028
E n t e r a s t r i n g : How much s t a c k s p a c e w i l l t h i s s t r i ng t a k e ?
Y o u e n t e r e d : H ow mu c h s ta c k s p a c e w i l l t h i s s t r i ng t a k e ?
Byt e s a v a i l a b l e o n s t a c k : 1 90 2
_arc Functions 86
#include <graph.h>
short _far _arc( short xl, short yl, short x2, short y2, short x3, short y3,
short x4, short y4 ) ;
short _far _arc_w( double xl , double yl , double x2, double y2, double x3, double y3,
double x4, double y4 );
short _far _arc_wxy( struct _wxycoord _far *pwxyl , struct _wxycoord _far *pwxy2,
struct _wxycoord _far *pwxy3, struct _wxycoord _far *pwxy4 ) ;
Remarks The _arc functions draw elliptical arcs. The center of the arc is the center of the bounding
rectangle, which is defined by points (xl , yl ) and (x2, y2) for _arc and _arc_w and by
points pwxyl and pwxy2 for _arc_wxy. The arc starts where it intersects an imaginary line
extending from the center of the arc through (.x3, y3) for _arc and _arc_w and through
pwxy3 for _arc_wxy. It is drawn counterclockwise about the center of the arc, ending
where it intersects an imaginary line extending from the center of the arc through (x4, y4)
for _arc and _arc_w and through pwxy4 for _arc_wxy.
The _arc routine uses the view coordinate system. The _arc_w and _arc_wxy functions
use the real-valued window coordinate system.
In each case, the arc is drawn using the current color. Since an arc does not define a closed
area, it is not filled.
87 _arc Functions
Return Value These functions return a nonzero value if the arc is successfully drawn; otherwise, they
retum O.
See Also _ellipse functions, _lineto functions, _pie functions, _rectangle functions, _setcolor
/ * A RC . C : T h i s p r o g r a m _d raws a s i mp l e a rc . * /
v o i d ma i n ( )
{
s hort x , y ;
s t ruct xyc o o r d xy s t a rt , xyend , xyf i l l ;
I * Fi nd a v a l i d g r a p h i c s mode * I
i f { ! _s et v i d eomod e ( _MAX R E SMODE ) )
exi t ( 1 ) ;
I * D raw a rc s */
x = 1 00 ; y = 1 00 ;
_a rc ( x 60 , y
- - 60 , x, y, x - 30 , y - 60 , x - 60 , y - 30 );
_a rc ( x + 6 0 , y + 60 , x, y, x, y + 30 , x + 30 , y );
getch ( ) ;
_s e t v i d e omod e ( _D E FAU LTMOD E ) ;
asctime 88
#include <time.h>
Rsmadrs The asctime function converts a time stored as a structure to a character string. The
timeptr value is usually obtained from a call to gmtime or localtime, both of which return
a pointer to a tm structure, defined in TIME.H. (See gmtime for a complete description of
the tm structure fields.)
The tm structure contains the following elements:
Element Description
int tm_sec Seconds after the minute (0-59)
int tm_min Minutes after the hour (0-59)
int tm_hour Hours since midnight (0-23)
The string result produced by asctime contains exactly 26 characters and has the form of
the following example:
Wed J a n 02 0 2 : 0 3 : 5 5 1 9 80 \ n \ 0
A 24-hour clock i s used. All fields have a constant width. The newline character (\n) and
the null character ( '\0 ') occupy the last two positions of the string. The asctime function
uses a single statically allocated buffer to hold the return string. Each call to this routine de
stroys the result of the previous call.
Rsturn Va/us The asctime function returns a pointer to the character string result. There is no error
return.
89 asctime
I * ASCT I M E . C : T h i s p r o g r a m pl a c e s t h e s y s t em t i me i n t h e l o n g i n t e g e r a c l o c k ,
* t r a n s l a t e s i t i n t o t h e s t r u c t u r e newt i me a n d t h en c o n v e r t s i t t o
* s t r i n g form f o r o u t p u t , u s i ng t h e a s c t i me f u n c t i on .
*I
#i n c l u d e < t i me . h >
#i n c l ude < s t d i o . h >
s t r u c t tm *newt i me ;
t i me_t a c l o c k ;
v o i d ma i n C l
(
t i me ( &a c l o c k > : I * G e t t i me i n s e c o n d s * /
/ * P r i n t l oc a l t i me a s a s t r i n g * /
p r i n t f ( " T h e c u r rent d a t e a n d t i me a re : % s \ n " , a s c t i me C n ewt i me ) ) ;
Output
T h e c u r rent d a t e a n d t i me a r e : T h u J u n 1 5 06 : 57 : 59 1 989
asin Functions 90
#include <math.h>
#include <errno.h>
Remarks The asin functions calculate the arcsine of x in the range -rc/2 to rt/2 radians. The value of
x must be between -1 and 1 . The asinl function is the 80-bit counterpart, which uses an 80-
bit, 1 0-byte coprocessor form of arguments and return values. See the reference page on
the long double functions for more details on this data type.
Return Value The asin functions return the arcsine result. If x is less than -1 or greater than 1 , asin sets
errno to EDOM, prints a DOMAIN error message to stderr, and returns 0.
Error handling can be modified by using the matherr (or _matherrl) routine.
Compatibility asin
asinl
S1111 Also acos functions, atan functions, cos functions, matherr, sin functions, tan functions
Example ������
I * AS I N COS . C : T h i s p ro g r a m p r ompts f o r a v a l ue i n t h e r a n ge -1 to 1 .
* I n p u t v a l ues o u t s i d e t h i s r a n g e wi l l p r o d u c e DOMA I N e r ro r mes s a ges .
* I f a v a l i d va l ue i s ente red , t h e p r o g r a m p r i n t s t h e a rc s i n e a n d t h e
* a rc c o s i n e o f t h a t v a l ue .
*I
#i n c l u d e <ma t h . h>
#i n c l u d e <stdi o . h>
#i n c l ude < s t d l i b . h>
#i n c l ude <errno . h>
91 asin Functions
v o i d ma i n ( )
{
doubl e x , y ;
p r i n t f ( " E n t e r a r e a l n um b e r b e t w e e n - 1 a n d 1 : " );
s c a n f ( " %l f " , &x ) ;
y = asin( x ) ;
p r i n t f ( " A r c s i n e of % f = % f \ n " , x , y l ;
y = a cos ( x ) ;
p r i n t f ( " A r c c o s i n e of %f = % f \ n " , x , y ) ;
Output
#include <assert.h>
#include <Stdio.h>
Remadrs The assert routine prints a diagnostic message and calls the abort routine if expression is
false (0). The diagnostic message has the form
where filename is the name of the source file and line number is the line number of the
assertion that failed in the source file. No action is taken if expression is true (nonzero).
The assert routine is typically used in program development to identify program logic er
rors. The given expression should be chosen so that it holds true only if the program is
operating as intended. After a program has been debugged, the special "no debug" identi
fier NDEBUG can be used to remove assert calls from the program. If NDEBUG is defined
(by any v alue) with a ID command-line option or with a #define directive, the C preproces
sor removes all assert calls from the program source.
#i n c l u d e < s t d i o . h >
#i n c l u d e < a s s e r t . h >
#i n c l ude < s t r i n g . h >
assert
v o i d a n a l y z e_s t r i n g ( c h a r * s t r i n g ) ; / * P rototype * /
v o i d ma i n ( )
(
. . .
c h a r t e s t l [ ] = " a bc " , * t e s t 2 = N U L L , t e s t 3 [ ] = .
I * Tes t s a s t r i ng to s e e i f i t i s N U L L , empty , o r l on g e r t h a n 0 c h a r a c t e r s * /
v o i d a n a l y z e_s t r i n g ( c h a r * s t r i n g )
(
a s sert< stri ng ! = NULL ) ; I * Ca nnot be N U L L */
a s sert < *stri ng ! = ' \0 ' > ; I * C a n n o t b e empty * /
a s s e r t ( s t r l en ( s t r i n g ) > 2 ) ; I * L e n g t h m u s t b e g re a t e r t h a n 2 * /
Output
An a l y z i n g s t r i n g ' a bc '
Ana l y z i n g s t r i n g ' ( n u l l ) '
A s s e rt i o n fa i l ed : s t r i n g ! = N U L L , f i l e a s s e rt . c , l i n e 2 8
a bn o rma l p r o g r a m t e rmi n a t i on
atan Functions 94
Description Calculate the arctangent of x (atan and atanl) and the arctangent of ylx (atan2 and atan21).
#include <math.h>
x, y Any number
Remarks The atan family of functions calculates the arctangent of x, and the atan2 family of func
tions calculates the arctangent of y/x. The atan group returns a value in the range -7r./2 to
7r./2 radians, and the atan2 group returns a value in the range -7t to 7t radians. The atan2
functions use the signs of both arguments to determine the quadrant of the return value.
Return Value The atan family of functions returns the arctangent result. If both arguments of atan2 or
atan21 are 0, the function sets errno to EDOM, prints a DOMAIN error message to stderr,
and returns 0.
Error handling can be modified by using the matherr (or _matherrl) routine.
atanl, atan21
SBB A/so acos functions, asin functions, cos functions, matherr, sin functions, tan functions
#i n c l u d e <ma t h . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < e r r n o . h>
95 atan Functions
v o i d ma i n ( )
I
doubl e x l , x2 , y:
Output
E n t e r a rea l n umbe r : - 8 6 2 . 42
A r c t a n gent of - 8 6 2 . 420000 : - 1 . 5 6 9 6 3 7
E n t e r a s e c o n d rea l n umbe r : 7 8 . 5 1 4 9
A rc t a n g ent of - 8 6 2 . 420000 I 78 . 5 1 4900 : - 1 . 480006
atexit 96
Remarks The atexit function is passed the address of a function <June) to be called when the pro
gram terminates normally. Successive calls to atexit create a register of functions that are
executed in LIFO (last-in-first-out) order. No more than 32 functions can be registered
with atexit or onexit. The functions passed to atexit cannot take parameters.
All routines passed to atexit should have the _loadds attribute if used in multithread
dynamic-link libraries.
Return Value The atexit function returns 0 if it is successful, or a nonzero value if an error occurs (e.g.,
if there are already 32 exit functions defined).
Use the ANSI-standard atexit function (rather than the similar onexit function) whenever
ANSI portability is desired.
In the OS/2 environment, the atexit function calls the OS/2 function DosExitList.
I * AT E X I T . C : T h i s p r o g r a m p u s h e s four f u n c t i on s o n t o t h e s t a c k of funct i on s
* t o b e e x e c u t e d w h e n a t ex i t i s c a l l ed . W h e n t h e p r o g r a m e x i t s , t h e s e
* p r o g rams a re exec u t ed on a " l a s t i n , f i r s t out " ba s i s .
*I
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
97 atexit
v o i d ma i n ( }
(
a t ex i t ( f n l > ;
a t ex i t ( fn2 } ;
a t e x i t ( fn3 } ;
a t ex i t ( fn4 } ;
p r i n t f ( " T h i s i s e x e c u t ed fi r s t . \ n " } ;
v o i d fn l C }
(
p r i n t f C " n ext . \ n " } ;
v o i d fn 2 ( }
(
p r i n t f ( • ex e c u ted • } ;
v o i d fn 3 C }
(
pri ntf( " i s • } ;
v o i d fn4 ( }
I
pri ntf( "Thi s " } ;
Output
T h i s i s executed f i r s t .
T h i s i s executed next .
atof, atoi, atol, _atold 98
Description Convert strings to double (atof), long double (_atold) integer (atoi), or long (atol).
Remades These functions convert a character string to a double-precision floating-point value (atof),
an integer value (atoi), a long integer value (atol); or a long double value (_atold). The
input string is a sequence of characters that can be interpreted as a numerical value of the
specified type.
The string size that can be handled by the atof or _atold function is limited to 100
characters.
The function stops reading the input string at the first character that it cannot recognize as
part of a number. This character may be the null character ( ' \0 ' ) terminating the string.
The atof and _atold functions expect string to have the following form:
[whitespaceD [ { sign ) D [ IKOdigitsD [.digitsD [ { d I D I e I E } [sign]digitsD
A whitespace consists of space and/or tab characters, which are 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 may be
followed by an exponent, which consists of an introductory letter (d, D, e, or E) and an op
tionally signed decimal integer.
The atoi and atol functions do not recognize decimal points or exponents. The string argu
ment for these functions has the form
[whitespaceD [signDdigits
where whitespace, sign, and digits are exactly as described above for atof.
99 atof, atoi, atol, _atold
Return Value Each function returns the double, long double, int, or long value produced by interpret
ing the input characters as a number. The return value is 0 (for atoi), OL (for atol), and 0.0
(for atof and _atold) if the input cannot be converted to a value of that type. The return
value is undefined in case of overflow.
_atold
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s td i o . h >
v o i d ma i n ( )
{
c h a r *s ; d o u b l e x; i n t i ; l on g 1 ;
s = • - 2 3 09 . 1 2 E - 1 5 " ; / * T e s t of a t of * /
x = atofC s ) ;
p r i n t f C • a t of test : A SC I I s t r i ng : % s \ t f l o a t : %e\n " , s , x );
s =• - 9885 p i g s " ; / * T e s t of a t o i * /
i =atoi C s ) ;
pri ntf( " atoi test : A SC I I s t r i n g : % s \ t \ t i n t eg e r : %d \ n " , s , );
Output
#include <dos.h>
int bdos( int dosfunc, unsigned int dosdx, unsigned int dosal );
Remades The bdos function invokes the DOS system call specified by dosfunc after placing the
values specified by dosdx and dosal in the DX and AL registers, respectively. The bdos
function executes an INT 2 1 H instruction to invoke the system call. When the system call
is complete, bdos returns the contents of the AX register.
The bdos function is intended to be used to invoke DOS system calls that either take no
arguments or take arguments only in the DX (DH, DL) and/or AL registers.
Do not use the bdos function to call interrupts that modify the DS register. Instead, use the
intdosx or int86x function. The intdosx and int86x functions load the DS and ES registers
from the segregs parameter and also store the DS and ES registers into segregs after the
·
function call.
This call should not be used to invoke system calls that indicate errors by setting the carry
· flag. Since C programs do not have access to this flag, your program cannot determine
whether the return value is an error code. The intdos function should be used in these
cases.
Return llatue The bdos function returns the value of the AX register after the system call has completed.
v o i d ma i n ( )
(
I * Offset of s t r i n g mu s t be i n D X , segment i n D S . A L i s not needed ,
* s o 0 i s u s ed .
*/
bdos C 0x09 , ( i n t ) s t r , 0 ) ;
Output
Hel l o worl d !
103 _beginthread
RemalkB The _beginthread function creates a thread that begins execution of a far routine at
start address. When the thread returns from that far routine, it is terminated automatically.
The user can also terminate the thread by calling endthread.
-
The address of the thread stack is given by stack_bottom. If stack_bottom is set to NULL,
the run-time library code will allocate and deallocate the thread stack as needed. Since the
_beginthread function can determine the current status of all thread IDs, it can free the old
stack and allocate a new stack whenever a thread is reused.
If it is not NULL, the stack_bottom argument must specify a word address, and the stack
must be at least as long as specified by the stack_size argument. Usually this memory is
either a global array or memory returned by malloc or _fmalloc.
practice in multithread programming is to make the first thread the main thread and wait
All threads will be tenninated if any thread calls abort, exit, exit, or DosExit. A good
The OS/2 function DosCreateThread should not be called directly to create threads. The
_beginthread function perfonns initialization procedures required to call other C run-time
library functions safely.
Return Value The function returns the thread identification number of the new thread, if successful. A re
turn value of -1 indicates an error, and errno is set to one of the following values:
Value Meaning
I * B EGTH RD . C i l l u s t ra t e s mul t i p l e t h re a d s u s i n g f u n ct i o n s :
* _beg i n t h r e a d _en d t h r e a d
*
* Al s o t h e g l oba l v a r i a b l e :
* _t h r ea d i d
*
* T h i s p r o g r a m req u i res t h e mul t i t h re a d l i b ra ry . For e x a mp l e , c omp i l e
* w i t h t h e f o l l ow i n g c omma nd l i n e :
* C L / MT TH READS . C
*I
#d e f i n e I N C L_NOCOMMON
fld e f i n e i N C L_NO P M
#d e fi n e I N C L_DOS P ROC E S S
I/d e f i n e I N C L_V I O
#i n c l u d e < o s 2 . h >
#i n c l u d e < p ro c e s s . h > / * _beg i nt h r ead , _en d t h r e a d * /
#i n c l u d e < s tddef . h > / * _t h r ea d i d */
#i n c l u d e < s t d l i b . h >
#i n c l u d e < c on i o . h >
v o i d ma i n ( )
{
PCHAR s ta c k :
CHAR ch = 'A' ;
/ * B o u n c e - T h r e a d t o c r e a t e a n d c o n t r o l a c o l o red l et t e r t h a t m o v e s
* a round o n t h e s c reen .
*
* P a rams : c h - t h e l et t e r t o be moved
*I
v o i d Boun c e ( i nt ch
(
/ * Gen e r a t e l et t e r a n d col o r a t t r i bute f rom t h re a d a rg ument . * /
char b l a n kc e l l [ 2 ] = ( 0x20 , 0x07 l :
char bl ockcel l [ 2 ] = ( c h , ( ch % 16> + 1 l :
i nt x o l d , x c u r , yol d , y c u r ;
BOO L f i r s t = T RU E :
_beginthread 106
/ * S e e d r a n d om n um b e r g e n e r a t o r a n d g e t i n i t i a l l o c a t i on . * /
s r a n d ( *_t h r e a d i d ) ;
x c u r - G e t Ra n d om ( 0 , vmi . c o l - 1 );
y c u r = Get Ra n d om < 0 , vmi . row - 1 l;
whi l e < repea t )
(
I * P a u s e b e t w e e n l oo p s . * /
DosSl eep ( 100L l ;
I * B l a n k o u t o u r o l d p o s i t i o n o n t h e s c reen , a n d d r aw n ew l e t t e r . * /
i f ( fi rst )
f i r s t .. FA L S E ;
el se
V i oWrt C e l l St r ( b l a n k c e l l , 2 , y o l d , x o l d , 0 ) ;
V i o W r t C e l l St r ( b l o c k c e l l , 2 , y c u r , x c u r , 0 ) ;
I * I n c rement t h e c o o rd i n a t e f o r n e x t p l a cement o f t h e b l o c k . * /
xol d = xcu r ;
yol d = yc u r ;
xcur += Get Ra n d om ( - 1 , 1 );
ycur += Get Random( - 1 , 1 l;
I * C o r r e c t p l a c ement < a n d b e e p ) i f a b o u t t o g o o f f t h e s c r e e n . * I
i f ( xcur < 0 )
xcur "' 1 ;
el se i f ( x c u r == v m i . c o l
xcur = vmi . col - 2 ;
el se i f ( ycur < 0 )
ycur = 1;
el se i f ( y c u r � v m i . row
ycur = v m i . row - 2 ;
I * I f n o t a t s c r e e n b o rd e r , c o n t i n u e , o t h e rw i s e b e e p . * /
e ls e
cont i nue ;
D o s B e e p ( ( c h - ' A ' l * 1 00 , 1 7 5 l ;
I * _e n d t h r e a d g i v e n ( b u t n o t r e a l l y n e e d ed ) to t e rm i n a t e . * /
_e n d t h r e a d ( ) ;
107 Bessel Functions
#include <math.h>
x Floating-point value
n Integer order
Remarks The jO, jl, and jn routines return Bessel functions of the first kind-orders 0, 1 , and n,
respectively.
The yO, yl, and yn routines return Bessel functions of the second kind-orders 0, 1 , and n,
respectively. The argument x must be positive.
The long double versions of these functions are the 80-bit counterparts and use the 80-bit,
1 0-byte coprocessor form of arguments and return values. See the reference page on the
long double functions for more details on this data type.
The Bessel functions are explained more fully in most mathematics reference books, such
as the Handbook ofMathematical Functions (Abramowitz and Stegun; Washington: U.S.
Government Printing Office, 1 964). These functions are commonly used in the mathemat
ics of electromagnetic wave theory.
Bessel Functions 108
For yO, yl, or yn, if x is negative, the routine sets errno to EDOM, prints a DOMAIN error
message to stderr, and returns -HUGE_VAL.
Error handling can be modified by using the matherr (or _matherrl) routine.
v o i d ma i n ( )
(
d o u b l e x = 2 . 387 ;
i nt n = 3, c;
Output
B e s s e l funct i on s f o r x = 2 . 387000 :
Ki nd Order Fun c t i on Re s u l t
Remarks The _bfreeseg function frees a based heap. The seg argument is a based heap returned by
an earlier call to _bheapseg. It specifies the based heap to be freed.
The number of bytes freed is the number of bytes specified when the block was allocated.
After the call, the freed heap is again available for allocation.
Return Value The _bfreeseg function returns 0 if successful and -1 in the case of an error.
See Also _bheapseg, calloc functions, free functions, malloc functions, realloc functions
/ * BH EAP S EG . C : T h i s p r o g r a m C i l l u s t ra t e s dynami c a l l oc a t i on of ba s ed
* memo ry u s i n g f u n c t i o n s _bh e a p s e g , _bf r ee s e g , _bma l l oc , a n d _bf ree .
*I
#i n c l u d e <stdi o . h>
#i n c l u d e <ma l l oc . h >
#i n c l u d e <stdl i b . h>
#i n c l u d e <stri ng . h>
v o i d ma i n ( )
(
_s egment s e g ;
c h a r _ba s e d ( s e g * ou t s t r , _ba s e d ( s e g *i nstr ;
c h a r _ba s e d ( s e g *pout , _b a s ed ( s e g *pi n ;
c h a r tmp s t r [ 80 ] ;
i nt l en ;
i f( C s e g • _b h e a p s e g ( 1 000 ) ) .... _N U L L S E G )
exi t ( 1 ) ;
I * A l l o c a t e ba s ed memo ry f o r two s t r i n g s . * /
II
l e n .. s t r l e n C tmp s t r ) ;
i f ( ( ( i n s t r .. _bma l l o c C s e g , J e n + 1 ) ) .... _N U L L O F F )
C C o u t s t r - _bma l l oc C s e g , l e n + 1 ) ) .... _NU L LO F F > )
exi t ( 1 ) ;
I * C o py a l ow e r c a s ed s t r i n g t o dy n a m i c memo ry . T h e b a s e d memo ry i s
* fa r w h e n a d d re s s ed a s a w h o l e .
*I
_f s t r l w r C _f s t rc py ( ( c h a r _fa r * ) i n s t r , ( c h a r _fa r * ) tmps t r ) ) ;
I * C o py i n p u t s t r i n g t o o u t p u t s t r i n g i n r e v e r s ed o r d e r . W h e n r e a d i n g
* a nd w r i t i n g i n d i v i d u a l c h a r a c t e r s f r om a ba s ed h e a p , t h e c om p i l e r w i l l
* t ry t o p r o c e s s t h em a s n ea r , t h u s s p e ed i n g u p t h e p r o c e s s i n g .
*I
fo r ( p i n i n s t r + l en - 1 , p o u � .. o u t s t r ;
m
I * D i s p l a y s t r i n g s . A g a i n s t r i n g s a s a w h o l e a r e fa r . * I
pri ntf( " I nput : SFs \ n " , ( c h a r _fa r * ) i n s t r ) ;
pri ntfC • output : SFs\ n " , ( c h a r _fa r * ) o u t s t r > ;
I * F r e e b l o c k s a n d r e l e a s e ba s ed h e a p . * /
_b f r ee C s e g , i n s t r > ;
_b f r ee C s e g , o u t s t r > ;
_b f r e e s e g C s eg > ;
Output
E n t e r a s t r i n g : Wa s I g o d
I nput : wa s i g o d
Output : dog i saw
_bheapseg 112
R1matb The _bheapseg function allocates a based-heap segment of at least size bytes. (The block
may be larger than size bytes because of space required for alignment and for maintenance
infonnation.)
The heap code will try to enlarge the heap as necessary. If the original block of memory is
depleted (e.g., by calls to _bmalloc and _brealloc), the run-time code will try to enlarge
the heap as necessary.
The value returned by _bheapseg is the identifier of the based-heap segment. This value
should be saved and used in subsequent calls to other based-heap functions.
The _bheapseg function can be called repeatedly. For each call, the C library will allocate
a new based-heap segment.
Return Value The _bheapseg function returns the newly allocated segment selector that the user must
save for use in subsequent based-heap functions. A return value of -1 indicates failure.
Always check the return from the _bheapseg function (especially when it is used in real
mode), even if the amount of memory requested is small.
S11 Also calloc functions, free functions, malloc functions, realloc functions
/ * B H E A P S E G . C : T h i s p r o g r a m C i l l u s t r a t e s dynami c a l l o c a t i on of b a s ed
* memory u s i n g funct i on s _b h e a p s e g , _bf r e e s eg , _bma l l oc , a nd _bf r e e .
*I
v o i d ma i n ( )
{
_s egment s e g ;
c h a r _ba sed ( s e g *out s t r , _ba sed ( s e g *i nstr ;
c h a r _ba sed ( s e g *pout , _ba sed ( s e g *pi n ;
c h a r tmp s t r [ 80 J ;
i n t l en ;
p r i n t f ( " En t e r a s t r i ng : " ) ;
g et s ( tmps t r ) ;
exi t ( l ) ;
exi t ( l ) ;
/ * C opy i n p u t s t r i n g t o output s t r i n g i n r e v e r s e d o r d e r . W h e n re a d i n g
* a nd w r i t i n g i n d i v i d u a l c h a r a c t e r s from a b a s ed h ea p , t h e c omp i l e r w i l l
* t ry t o p r o c e s s t h em a s nea r , t h u s speed i n g u p t h e p r o c es s i n g .
*I
fo r ( p i n = i n s t r + l en - l , p o u t = out s t r ;
pout < o u t s t r + l en ; p i n - - , pou t++ )
*pout = *pi n ;
*pout = ' \ 0 ' ;
I * D i s p l ay s t r i n g s . Ag a i n , s t r i n g s a s a w h o l e a re fa r . * /
p r i n t f ( " I n p u t : % Fs \ n " , ( c ha r _fa r * ) i n s t r ) ;
p r i n t f ( " O u t p u t : % F s \ n " , < c ha r _fa r * l ou t s t r ) ;
I * F ree b l o c k s a n d rel ea s e b a s ed h ea p . * /
_b free ( s e g , i n s t r ) ;
_b free ( s e g , o u t s t r ) ;
_bf r ee s eg ( s e g ) ;
_bheapseg 114
Output
E n t e r a s t r i n g : Wa s I god
I n put : wa s i god
Output : d o g i s a w
1 15 _bias_ disk
#include <bios.h>
Remalks The _bios_disk routine uses system call INT Ox l 3 to provide several disk-access func
tions. The service parameter selects the function desired, while the diskinfo structure pro
vides the necessary parameters. Note that the low-level disk operations allowed by the
_bios_disk routine are very dangerous to use because they allow direct manipulation of
the disk.
Element Description
unsigned drive Drive number
void far *buffer Memory location to write to, read from, or compare
The service argument can be set to one of the following manifest constants:
Constant Function
_DISK FORMAT
_ Formats the track specified by diskinfo. The head and track
fields indicate the track to format. Only one track can be for
matted in a single call. The biiffer field points to a set of sector
markers. The format of the marlcers depends on the type of
disk drive; see a technical reference to the PC BIOS to deter
mine the marlcer format. There is no return value.
_bias_ disk 116
DISK READ
_ _ Reads one or more disk sectors into memory. This service
uses all fields of the structure pointed to by diskinfo, as de
fined earlier in this section. If no error occurs, the function re
turns 0 in the high-order byte and the number of sectors read
in the low-order byte. If there is an error, the high-order byte
will contain a set of status flags. If there is an error, the high
order byte will contain a set of status flags, as defined under
_ DISK READ Status is returned in the 8 high-order bits of
_ .
Bits Meaning
_ DISK RESET Forces the disk controller to do a hard reset, preparing for
floppy-disk 1/0. This is useful after an error occurs in another
_
_DISK VERIFY
_ Checks the disk to be sure the specified sectors exist and can
be read. It also runs a CRC (cyclic redundancy check) test.
This service uses all fields (except buffer) of the structure
pointed to by diskinfo, as defined earlier in this section. If no
error occurs, the function returns 0 in the high-order byte and
the number of sectors compared in the low-order byte. If there
is an error, the high-order byte will contain a set of status
flags, as defined under _DISK READ
_ (above).
_DISK WRITE
_ Writes data from memory to one or more disk sectors. This
service uses all fields of the structure pointed to by diskinfo,
as defined earlier in this section. If no error occurs, the func
tion returns 0 in the high-order byte and the number of sectors
written in the low-order byte. If there is an error, the high
order byte will contain a set of status flags, as defined under
_ DISK READ
_ (above).
Retum Value The _bios_disk function returns the value in the AX register after the BIOS interrupt.
&• ��
����---
I * BD I S K . C : T h i s p r o g r a m f i r s t a t t empts to v e r i fy a d i s k by u s i ng a n
* i n v a l i d d i s k h e a d n umbe r . Aft e r p r i n t i ng t h e return v a l ue e r r o r code ,
* t h e p rog r a m v e r i fi es t h e d i s k by u s i n g a v a l i d d i s k h e a d code .
*I
#i n c l u d e < c o n i o . h >
#i n c l u d e < s t d i o . h>
#i n c l u d e < b i os . h >
v o i d ma i n ( )
(
u n s i gned s t a t u s = 0 ;
s t r uct d i s k i nfo_t d i s k_i n f o ;
d i s k_i n fo . d r i v e = 0;
d i s k_i nfo . h e a d = 10 ; / * I n v a l i d h e a d number * /
d i s k_i nfo . t ra c k = l;
d i s k_i nfo . s e c t o r 2;
d i s k_i nfo . n s e c t o r s = 8 ;
=
_bias_ disk 1 18
p r i n t f ( " I n s e rt d i s k i n d r i v e A : a n d p r e s s a ny k ey \ n " ) ;
getch ( ) ;
s t a t u s = _b i os_d i s k C _D I S K_V E R I FY , & d i s k_i nfo ) ;
p r i n t f ( " Re t u r n v a l u e : 0x% . 4x \ n " , s t a t u s ) ;
i f ( s t a t u s & 0xff00 ) / * E r r o r i f h i g h byte i s 0 * /
p r i n t f ( " Se e k e r r o r \ n " > :
el se
p r i n t f ( " No s e e k e r ro r \ n " > :
p r i n t f C " P re s s a ny k ey \ n " ) ;
getc h C ) ;
d i s k_i n f o . h e a d
= 0; / * V a l i d h e a d n umbe r * /
s t a t u s = _b i os_d i s k ( _D I S K_V E R I FY , & d i s k_i nfo > :
p r i n t f ( " Re t u r n v a l u e : 0x% . 4x \ n " , s t a t u s > :
i f ( s t a t u s & 0x ff00 ) / * E r r o r i f h i g h by te i s 0 * /
p r i n t f ( " Se e k e r ro r \ n " ) ;
el se
pri ntf ( " No seek error\ n " ) ;
Outpul
I n s e rt d i s k i n d r i v e A : a nd p r e s s a ny key
Ret u rn v a l u e : 0x0400
Seek e r r o r
P r e s s a ny k ey
Ret u rn v a l u e : 0x0008
No seek error
1 19 _bios_equiplist
Description Calls BIOS equipment-list service, using system call INT Oxl 1 .
#include <bios.h>
Remarks The _bios_equiplist routine uses system call INT Ox l l to determine what hardware and
peripherals are currently installed on the machine.
Return Value The function returns a set of bits indicating what is installed, as defined below:
Bits Meaning
I * B EOU I P L I . C : T h i s p r o g r a m c h e c k s f o r t h e p r e s e n c e of d i s kettes . * /
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
_bios_equiplist 120
v o i d ma i n ( )
I
uns i gned e q u i pment ;
e q u i pment = _b i o s_e q u i p l i s t ( ) ;
p r i n t f ( " Eq u i pment b i t s : 0x% . 4x \ n " , e q u i pment ) ;
i f ( e q u i pment & 0x 1000 ) / * C h e c k f o r g a me a d a pt e r b i t * /
p r i n t f ( " Game a d a pt e r i n s t a l l ed \ n " l ;
el se
p r i n t f ( " N o g a me a d a p t e r i n s t a l l ed \ n " l ;
Output
E q u i pment b i t s : 0x40 6 1
N o g ame a d a pt e r i n s t a l l ed
121 _bios_keybrd
Remarks The _bios_keybrd routine uses system call INT Ox 1 6 to access the ke)'board services. The
service argument can be any of the following manifest constants:
Constant Meaning
_KEYBRD_READ, Reads the next character from the key
_NKEYBRD_READ board. If no character has been typed, the
call will wait for one. If the low-order
byte of the return value is nonzero, the
call contains the ASCII value of the char
acter typed. The high-order byte contains
the keyboard scan code for the character.
The NKEYBRD READ constant is used
withenhanced keyboards to obtain the
scan codes for function keys FI I and F12
and the cursor control keys.
_KEYBRD_READY, y
Checks whether a ke stroke is waiting to
_NKEYBRD_READY be read and, if so, reads it. The return
value is 0 if no keystroke is waiting, or it
is the character waiting to be read, in the
same format as the _KEYBRD_READ or
_NKEYBRD_READY return. This service
does not remove the waiting character
from the input buffer, as does the
_KEYBRD_READ or _NKEYBRD_READ
service. The NKEYBRD READY con
stant is used ;ith enhanc ed keyboards to
obtain the scan codes for function keys Fl I
and FI2 and the cursor control keys.
_bios_keybrd 122
Return Value With the ""READ and SHIFrSTATUS arguments, the _bios_keybrd function returns the
•••
I* B K EY B RD . C : T h i s p r o g r a m p r i n t s a mes s a ge on t h e s c reen u n t i l t h e
* r i g h t S H I FT k ey i s p res s ed .
*I
#i n c l u d e < b i os . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n { )
(
w h i l e { ! { _b i os_keyb rd { _KEY BRD_S H I FTSTATUS ) & 000 1 ) )
p r i n t f { " U s e t h e r i g h t SH I FT k ey to stop t h i s mes s a g e \ n " ) ;
p r i n t f { " Ri g h t SH I FT k ey pres s ed \ n " > :
Output
Description Calls the BIOS memory-size service, using system call INT Ox1 2.
#include <bios.h>
Rematts The _bios_memsize routine uses system call INT Ox 1 2 to detennine the total amount of
main memory installed.
Return Value The routine returns the total amount of installed memory in lK blocks. The maximum re
turn value is 640, representing 640K of main memory.
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
u n s i g n e d memo ry ;
memo ry = _b i os_mems i z e C ) :
p r i n t f C " T h e amount of memo ry i n st a l l ed i s : % d K \ n " , memory l;
Output
T h e amount o f memo ry i n s t a l l ed i s : 6 3 9 K
125 _bias_printer
#include <bios.h>
Remarks The _bios_printer routine uses system call INT Ox 17 to perfonn printer output services
for parallel printers. The printer argument specifies the affected printer, where 0 is LPT l ,
1 i s LPT2 , and s o forth.
Some printers do not support the full set of signals. As a result, the "Out of Paper" condi
tion, for example, may not be returned to your program.
The service argument can be any of the following manifest constants:
Constant Meaning
_PRINTER_INIT Initializes the selected printer. The data argument is ignored.
The return value is the low-order status byte defined below.
_PRINTER_STATUS Returns the printer status in the low-order status byte defined
below. The data argument is ignored.
_PRINTER_WRITE Sends the low-order byte of data to the printer specified by
printer. The low-order byte of the return value indicates the
printer status after the operation, as defined below:
R11tum Value The _bios_printer function returns the value in the AX register after the BIOS interrupt.
Exampm �����
/ * B P R I N T E R . C : T h i s p r o g r a m c h e c k s t h e s t a t u s of t h e p r i n t e r a t t a c Hed t o
* L P T l w h e n i t i s off l i ne , t h e n i n i t i a l i z es t h e p r i n t e r .
*/
#i n c l u d e < b i o s . h >
#i n c l u d e < c o n i o . h >
#i n c l u d e < s t d i o . h >
/ld efi n e L P T l 0
v o i d ma i n ( )
(
uns i gned status ;
s t a t u s = _b i o s_p r i n t e r C _P R I NT E R_I N I T , L P T l , 0 ) ;
p r i n t f ( " St a t u s a f t e r p r i n t e r i n i t i a l i z ed : 0x% . 4x \ n " , s t a t u s > :
Output
P l a c e p r i n t e r off l i n e a nd p r e s s a ny k ey
S t a t u s w i t h p r i n t e r off l i n e : 0x00 1 8
P u t t h e p r i n t e r on l i n e a n d t h e n
P r e s s a ny k ey to i n i t i a l i ze p r i n t e r
S t a t u s a ft e r p r i n t e r i n i t i a l i z ed : 0x0090
127 _bios_serialcom
Daer/pt/an Calls BIOS communications services, using system call INT Ox1 4.
#include <bios.h>
Remades The _bios_serialcom routine uses system call INT Ox14 to provide serial communications
. services. The serial_port argument is set to 0 for COM l , to 1 for COM2, and so on.
The _bios_serialcom routine may not be able to establish reliable communications at baud
rates in excess of 1 ,200 baud ( _COM_1200) due to the overhead associated with servicing
computer interrupts. Faster data communication rates are possible with more direct pro
gramming of serial-port controllers. See C Programmer's Guide to Serial Communications
for more details on serial-communications programming in C.
The service argument can be set to one of the following manifest constants:
Constant Service
_COM_INIT Sets the port to the parameters specified in the data argument
_COM_SEND Transmits the data characters over the selected serial port
_COM_RECEIVE Accepts an input character from the selected serial port
_COM_STATUS Returns the current status of the selected serial port
Constant Meaning
_COM_CHR7 7 data bits
_COM_CHR8 8 data bits
_COM_STOPl 1 stop bit
_COM_STOP2 2 stop bits
_COM_NOPARITY No parity
_bios_serialcom 128
Return Value The function returns a 1 6-bit integer whose high-order byte contains status bits. The mean
ing of the low-order byte varies, depending on the service value. The high-order bits have
the following meanings:
15 Timed out
14 Transmission-shift register empty
13 Transmission-hold register empty
12 Break detected
11 Framing error
10 Parity error
9 Overrun error
8 Data ready
When service is _COM_SEND, bit 15 will be set if data could not be sent.
When service is _COM_RECEIVE, the byte read will be returned in the low-order bits if
the call is successful. If an error occurs, any of the bits 9, 10, 1 1 , or 15 will be set.
129 _bias_ssrialcam
When service is -COM-INIT or -COM -STATUS, the low-order bits are defined as
follows:
Note that this function works only with IBM personal computers and true compatibles.
I* B S E R I A LC . C : T h i s p r o g r a m c h e c k s t h e s t a t u s of s e r i a l p o r t COM l . * /
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
I
u n s i gned c oml_s ta t u s ;
Output
C O M l s t a t u s : 0x6000
130
D•t:rlptlon Calls BIOS time and date services, using system call INT Ox lA.
#include <bios.h>
Rematb The _bios_timeofday routine uses system call INT OxlA to get or set the clock count. The
service argument can be either of the following manifest constants:
Constant Meaning
_TIME_GETCLOCK Copies the current value of the clock count to the location
pointed to by timeval. If midnight has not passed since the last
time the system clock was read or set, the function returns O;
otherwise, the function returns 1 .
_TIME_SETCLOCK Sets the current value of the system clock to the value in the
location pointed to by timeval. There is no return value.
Rllum Value The _bios_timeofday function returns the value in the AX register after the BIOS
interrupt.
I
i
Exampm �-+-����---
1 * BT I M EO F D lC: T h i s p r o g r a m g e t s t h e c u r rent sys tem c l o c k count before a n d a ft e r
* a "do-no yhi ng• l oop a n d d i s p l a y s t h e d i fference .
*I
i
I
i
v o i d ma i n { )
(
l ong i , b e g i n_t i c k , end _t i c k ;
fo r { i = l ; i <= 900000 ; i ++ )
p r i n t f { " Be g i n n i ng t i c k count : %l u \ n " , b e g i n_t i c k ) ;
tlutput
B e g i n n i ng t i c k count : 1 1 1 4 2 5 5
E nd i n g t i c k c o u n t : 1 1 14287
E l a ps ed t i c k s : 32
bsean:hl 132
Remarks The bsearch function perfonns a binary search of a sorted array of num elements, each of
width bytes in size. The base value is a pointer to the base of the array to be searched, and
key is the value being sought.
The compare argument is a pointer to a user-supplied routine that compares two array ele
compare routine one or more times during the search, passing pointers to two array ele
ments and returns a value specifying their relationship. The bsearch function calls the
ments on each call. The routine compares the elements, then returns one of the following
values:
Value Meaning
If the array you are searching is not in ascending sort order, bsearch does not work prop
erly. If the array contains duplicate records with identical keys, there is no way to predict
which of the duplicate records will be located by bsearch.
Return Va/us The bsearch function returns a pointer to the first occurrence of key in the array pointCd to
by base. If key is not found, the function returns NULL.
133 bsearch
#i n c l u d e < s e a r c h . h >
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h > ·
v o i d ma i n ( i n t a r gc , c h a r * * a r g v }
(
cha r **resul t ;
c h a r * k ey = " c a t " ;
i nt i ;
I * Sort u s i n g Q u i c k s o rt a l g o r i t hm : * /
q s o rt ( ( c h a r * } a rg v , a rg c , s i z eo f ( c h a r * } , c omp a re > :
I * Fi n d t h e word • c a t • u s i n g a b i n a ry s e a r c h a l g o r i t hm : * /
res u l t = C c h a r ** ) b s e a rc h C ( c h a r * ) & k ey , ( c h a r * ) a rg v , a r gc ,
s i zeof C c ha r * } , c ompa re > :
i f ( res u l t >
p r i n t f C " \ n%s foun d a t % F p \ n " , * r e s u l t , r e s u l t > :
el se
p r i n t f ( " \ n C a t n o t found ! \ n " > :
Output
[ C : \ L I BR E F J b s e a r c h d o g p i g h o r s e c a t h uma n r a t c ow goa t
b s e a r c h c a t c ow dog g o a t h o r s e h uma n p i g r a t
c a t f o u n d a t 0 2 9 2 : 0 FD0
I
cabs, ca sl fI
134
#include <math.h>
. z Complex number
Remarks The cabs and cabsl functions calculate the absolute value of a complex number, which
must be a structure of type complex (or _complexl). The structure z is composed of a real
component x and an imaginary component y. A call to one of the cabs routines is equiv
alent to the following:
The cabsl function is the 80-bit counterpart and it uses the 80-bit, 10-byte coprocessor
form of arguments and return values. See the reference page on the long double functions
for more details on this data type.
Return Value On overflow, these functions call matherr or _matherrl, return HUGE_VAL, and set
ermo to ERANGE.
Campallblllly cabs
cabsl
Exampm �-+����������������������������---
�
1 * CABS . C : U i n g c a b s , t h i s p r o g r a m c a l c u l a t e s t h e a b s o l ute va l u e of
* a c omp l e�. n umber .
*/
I
#i n c l ude <ma t h . h >
#i n c l ude < s t � i o . h >
135 cabs, cabs/
v o i d ma i n ( )
(
s t r uct c omp l ex n umbe r = ( 3 . 0 , 4 . 0 J ;
doubl e d ;
d = c a b s ( number ) ;
p r i n t f ( " T h e a b s o l u t e v a l ue o f % f + %fi i s % f \ n " ,
n umbe r . x , n umbe r . y , d ) ;
Output
136
I
Daer/pt/an I Allocate an array in memory with elements initialized to 0.
I
I
Remarks The calloc family of functions allocates storage space for an array of num elements, each
of length size bytes. Each element is initialized to 0.
In large data models (compact-, large-, and huge-model programs), calloc maps to
_fcalloc. In small data models (tiny-, small-, and medium-model programs), calloc maps
to _ncalloc.
The various calloc functions allocate storage space in the data segments shown in the list
below:
Function Data Segment
calloc Depends on data model of program
_bcalloc Based heap, specified by seg segment selector
fcalloc Far heap (outside default data segment)
_ncalloc Near heap (inside default data segment)
Return Value The calloc functions return a pointer to the allocated space. The storage space pointed to
by the return value is guaranteed to be suitably aligned for storage of any type of object.
To get a pointer to a type other than void, use a type cast on the return value.
The _fcalloc and _ncalloc functions return NULL if there is insufficient memory available
or if num or size is 0. The _bcalloc function returns _NULLOFF in this case.
137 ca/lac Functions
Compatibility canoe
See Also free functions, halloc, hfree, malloc functions, realloc functions
I * C A L LOC . C : T h i s p r o g r a m u s e s c a l J oc t o a l l o c a t e s p a c e f o r 40 l on g i n t e g e r s .
* I t i n i t i a l i z e s ea c h e l eme n t t o z e ro .
*/
#i n c l u d e < s t d i o . h >
#i n c l u d e <ma l l oc . h >
v o i d ma i n ( )
(
l on g *buffe r ;
b u f f e r = ( l o n g * ) c a l l oc C 40 , s i zeof ( l on g ) > :
i f ( buffer ! = N U L L )
p r i n t f C " A l l o c a t ed 40 l ong i n t e g e r s \ n " > :
el s e
p r i n t f ( " Ca n ' t a l l o c a t e memo ry \ n " ) ;
free ( buffer > :
Output
Al l o c a ted 40 l on g i nt e g e r s
ceil, ce if 138
I
I
#include <math.h>
x Floating-point value
Remarks The ceil and ceill functions return a double (or long double) value representing the
smallest integer that is greater than or equal to x.
The ceill function is the 80-bit counterpart and it uses the 80-bit, 1 0-byte coprocessor fonn
of arguments and return values. See the reference page on the long double functions for
more details on this data type.
Relum Value These functions return the double or long double result. There is no error return.
Campallblllly ceil
ceill
Examp� �-+------
1
I * F LOOR . C : T h i s examp l e d i s p l a y s t h e l a rg e s t i n t e g e r s l es s t h a n o r equa l
* t o t h e f o a t i n g - po i n t v a l ues 2 . 8 a nd - 2 . 8 . I t t h e n s h ows t h e sma l l e s t
* i n t e g e r s g r e a t e r t h a n o r e q u a l t o 2 . 8 and - 2 . 8 .
I
*I I
!
I
139 ceil, ceill
v o i d ma i n ( )
{
doubl e y;
y = fl oo r ( 2 . 8 ) ;
p r i n t f ( " T h e fl o o r of 2 . 8 i s %f\ n " , y ) ;
y = fl o o r ( - 2 . 8 ) ;
p r i n t f { " Th e f l o o r o f - 2 . 8 i s % f \ n " , y ) ;
y = cei l ( 2.8 l ;
pri ntf ( "The cei l of 2 . 8 i s %f\ n " , y ) ;
y = cei l ( -2 . 8 ) ;
pri ntf ( "The cei l of - 2 . 8 i s %f\ n " , y ) ;
Output
Description Perform clean-up operations and return without terminating the process.
#include <process.h>
Remarks The _cexit function calls, in LIFO ("last in, first out") order, the functions registered by
atexit and onexit. Then the _cexit function flushes all 1/0 buffers and closes all open files
·
before returning.
The _c_exit function returns to the calling process without processing atexit or onexit
functions or flushing stream buffers.
The behavior of the exit, -exit, -cexit, and -c-exit functions is described in the following
list:
Function Action
exit Performs complete C library termination procedures, termi
nates the process, and exits with the supplied status code
_exit Performs "quick" C library termination procedures, terminates
the process, and exits with the supplied status code
_cexit Performs complete C library termination procedures and re
turns to caller, but does not terminate the process
_c_exit Performs "quick" C library termination procedures and re
turns to caller, but does not terminate the process
See Also abort, atexit, exec functions, exit, onexit, spawn functions, system
141 cgets
Remarks The cgets function reads a string of characters directly from the console and stores the
string and its length in the location pointed to by buffer. The buffer argument must be a
pointer to a character array. The first element of the array, buffer[O] , must contain the maxi
mum length (in characters) of the string to be read. The array must contain enough ele
ments to hold the string, a terminating null character ( '\0 ' ) , and two additional bytes.
The cgets function continues to read characters until a carriage-return-line-feed (CR-LF)
combination is read, or the specified number of characters is read. The string is stored
starting at str[2]. If a CR-LF combination is read, it is replaced with a null character ('\0')
before being stored. The cgets function then stores the actual length of the string in the sec
ond array element, buffer[ I ] .
Because all DOS editing keys are active when you call cgets, pressing F3 repeats the last
entry.
Return Value The cgets function returns a pointer to the start of the string, at buffer[2]. There is no error
return.
I * CGETS . C : T h i s p r o g r a m c r e a t e s a b u f f e r a n d i n i t i a l i z es t h e f i r s t by t e
* t o t h e s i z e of t h e b u f f e r - 2 . Next , t h e p r o g r a m a c c e p t s a n i n p u t s t r i n g
* u s i n g c g e t s a n d d i s p l a y s t h e s i z e a n d t e x t of t h a t s t r i n g .
*I
i
v o i d ma i n { )
{ I
r
char bufff r [82] = { 80 J ; / * M a x i mum c h a r a c t e r s i n f i r s t by t e * /
char *res l t ;
· t nput
l
p r i ntf ( l i n e of text , fol l owed by c a r r i a g e r e t u r n : \ n " ) ;
r e s u l t = f g et s ( b u f f e r ) ; / * I np u t a l i n e of text * /
p r i n t f ( " n l i ne l e n g t h = %d\ nText = % s \ n " , buffe r [ l ] , res u l t ) ;
t
Output ;
L i n e l en g t h 17t
T h i s i s s ome t e x t
j
T e x t = T h i s s s ome t ext
143 _chain_intr
#include <dos.h>
Remarks The _chain_intr routine passes control from one interrupt handler to another. The stack
and the registers of the first routine are passed to the second, allowing the second routine
to return as if it had been called directly.
The _chain_intr routine is generally used when a user-defined interrupt handler begins
processing, then chains to the original interrupt handler to finish proces�ing.
Chaining is one of two techniques, listed below, that can be used to transfer control from a
new interrupt routine to an old one:
1. Call _chain_intr with the interrupt routine as an argument. Do this if your routine is
fmished and you want the second interrupt routine to terminate the interrupt call.
++_d i ; / * I n i t i a l p r o c es s i ng h e r e * /
_c h a i n_i n t r ( ol d_i nt l ; / * N ew D I pa s s ed t o o l d_i n t * /
- -_d i ; / * T h i s i s n e v e r e x e c u t ed */
2 . Call the interrupt routine (after casting it to an interrupt function if necessary). Do this
if you need to do further processing after the second interrupt routine finishes.
++_d i ; I* I n i t i a l proces s i ng h e r e */
( * o l d_i nt l ( ) ; I * N ew D I pa s s ed t o ol d_i nt */
_a s m mov _d i , d i I * P u t rea l D I f rom o l d_i nt */
I* i n t o _d i f o r r e t u r n */
Note that the real registers set by the old interrupt function are not automatically set to the
pseudoregisters of the new routine.
_chain_f'' 144
Use the _chain_intr function when you do not want to replace the default interrupt han
dler, but you do need to see its input. An example is a TSR (terminate-and-stay-resident)
program that checks all keyboard input for a particular "hot key" sequence.
The _chain_intr function should be used only with C functions that have been declared
with type _interrupt. The _interrupt declaration ensures that the procedure's entry/exit
sequence is appropriate for an interrupt handler.
Return Value The _chain_intr function does not return to the caller.
I
Compatlb/llty 0 ANSI • DOS 0 OS/2 0 UNIX 0 XEN IX
Remarks The chdir function changes the current working directory to the directory specified by
dirname. The dirname argument must refer to an existing directory.
This function can change the current working directory on any drive; it cannot be used to
change the default drive itself. For example, if A: is the default drive and \BIN is the
current working directory, the following call changes the current working directory for
drive C:
c h d i r ( " c : \ \ t emp " ) ;
Notice that you must place two backslashes ( \\ ) in a C string in order to represent a single
backslash ( \ ) ; the backslash is the escape character for C strings and therefore requires
special handling.
This function call has no apparent immediate effect. However, when the _chdrive function
is called to change the default drive to C:, the current working directory becomes
C:\TEMP.
In OS/2 protected mode, the current working directory is local to a process rather than
system-wide. When a process terminates, the current working directory is restored to its
original value. Under DOS, the new directory set by the program becomes the new current
working directory.
Return Value The chdir function returns a value of 0 if the working directory is successfully changed. A
return value of -1 indicates an error, in which case errno is set to ENOENT, indicating
that the specified path name could not be found.
I * CHGD I R . 9 : T h i s p r o g r a m u s e s t h e c h d i r f u n c t i on to v e r i fy t h a t a
l
v o i d ma i n { 1 n t a rg c , c h a r *a rgv [ J )
i f { c h d il r c
( I
p r i n �f (
a rg v [ l ] > )
" Un a b l e t o l oc a t e t h e d i rec t o ry : % s \ n " , a rg v [ l ] l ;
I
s y s t �m C " d i r * . c • > :
el se
I
i
I
I
Output
[C : \ LI BREF � c h g d i r \ tmp
I
i
Remarks The _chdrive function changes the current working drive to the drive specified by drive.
The drive argument uses an integer to specify the new working drive ( l =A, 2=B, etc.).
This function changes only the working drive; the chdir function changes the working
directory.
In OS/2 protected mode, the working drive is local to a process rather than system-wide.
When a process terminates, the working drive is restored to its original value. Under DOS,
the new drive set by the program becomes the new working drive.
Return Value The _chdrive function returns a value of 0 if the working drive is successfully changed. A
return value of - 1 indicates an error.
See Also chdir, _dos_setdrive, _fullpath, _getcwd, _getdrive, mkdir, rmdir, system
I * GETD R I V