100% found this document useful (1 vote)
1K views864 pages

Microsoft C RunTime Library Reference

A Book About Microsoft C Run Time Library

Uploaded by

saurabhade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views864 pages

Microsoft C RunTime Library Reference

A Book About Microsoft C Run Time Library

Uploaded by

saurabhade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 864

icrosoft

Run!fime Library Reference

Microsoft Languages Library;

Written, edited, and produced


by Microsoft Corporation

Distributed by Microsoft Press ®


PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way, Redmond, Washington 98052-6399

Copyright© 1990 by Microsoft Press

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.

Library of Congress Cataloging-in-Publication Data

Microsoft C run-time library reference.

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

Printed and bound in the United States of America.

2 3 4 5 6 7 8 9 HCHC 3 2 I 0

Distributed to the book trade in Canada by General Publishing Company, Ltd.

Distributed to the book trade outside the United States and Canada by Penguin
Books Ltd.

Penguin Books Ltd., Harmondsworth, Middlesex, England


Penguin Books Australia Ltd., Ringwood, Victoria, Australia
Penguin Books N.Z. Ltd., 182-190 Wairau Road, Auckland I 0, New Zealand

British Cataloging in Publication Data available.

Writers: Editors: Sample Programs:


Phil Nelson Amanda Clark Bruce McKinney
Terry Ward Moira Macdonald
Marjorie Manwaring
Bill Nolan

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

PART 1 Over vie w

Chapter 1 Using CLibrary Routines . . . . . . . . . 5


1.1 Calling Library Routines . . . 5
1 .2 Using Header Files . . . . . . . . . • 6
1 .3 File Names and Path Names . . . . . . 9
1 .4 Choosing Between Functions and Macros IO
1 .5 Stack Checking on Entry . . . . 12
1.6 Handling Errors . . . . . . . 13
1 .7 Operating-System Considerations 14
1 .8 Floating-Point Support . . . . 15
1 .9 Using Huge Arrays with Library Functions 16

Cha pter2 Run-Time Routines by Category . . . . 19


2. 1 Buffer Manipulation . . . . . . . 20
2.2 Character Classification and Conversion 21
2.3 Data Conversion 22
2.4 Directory Control 23
2.5 File Handling 23
2.6 Graphics 25
2.7 Input and Output 35
2.8 Internationalization 45
2.9 Math . . . . . . 45
2. 1 0 Memory Allocation 48

Iii
Iv Microsoft C Run-Time Library Reference

2.11 Process and Environment Control . 51


2.12 Searching and Sorting . 55
2.13 String Manipulation . 55
2.14 System Calls . 56
2.15 Time . . . . . . . 60
2.16 Variable-Length Argument Lists . 62

Cha pter3 GlobalVariables andStandard Types . . . 63


3.1 _amblksiz . 63
3.2 daylight, timezone, tzname . . . . . . 64
3.3 _doserrno, errno, sys_errlist, sys_nerr . 65
3.4 _frnode . . . . . . . . . . . . . 66
3.5 _osmajor, _osminor, _osmode, _osversion . 67
3.6 environ . 67
3.7 _psp . . . . . 68
3.8 Standard Types . 68

PART 2 Run-Time Functions

About the Run-Time Reference . . . . . . . . • • • • • 75

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

• Fast and efficient routines to perform common programming tasks (such as


string manipulation), sparing you the time and effort needed to write such
routines
• Reliable methods of performing operating-system functions (such as opening
and closing files)

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.

About the C Run- Time Library


The Microsoft C run-time library contains a number of new routines and features
which support American National Standards Institute (ANSI) C compatibility,
OS/2 and XENIX® programming, and sophisticated graphics programming.
To ease the task of transporting programs from one operating system to another,
the description of each library routine includes compatibility boxes, which show
at a glance whetherthe routine is compatible with ANSI C, MS-DOS, OS/2,
UNIX®, and XENIX. (In this book, references to XENIX systems also encom­
pass UNIX and other UNIX-like systems.)

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.

OS/2 and XENIX@ Programming


Microsoft C run-time library routines are designed to maintain maximum com­
patibility between MS-DOS, OS/2, and XENIX or UNIX systems. The library
offers a number of operating-system interface routines that allow you to take
advantage of specific DOS and OS/2 features.
Most of the functions in the C library for DOS and OS/2 are compatible with like­
named routines in the C library for XENIX. For additional compatibility, the
math library functions have been extended to provide exception handling in the
same manner as the UNIX System V math functions.

Expanded Graphics Library


The Microsoft C run-time library now contains over one hundred graphics
routines. The core of this library consists of several dozen low-level graphics
routines, which allow your programs to select video modes, set points, draw
lines, change colors, and draw shapes such as rectangles and ellipses. You can
display real-valued data, such as floating-point values, within windows of differ­
ent sizes by using various coordinate systems.
Recent additions to the graphics library include presentation graphics and
fonts. The presentation-graphics library provides powerful tools for adding
presentation-quality graphics to your programs. These routines can display data
as a variety of graphs, including pie charts, bar and column charts, line graphs,
and scatter diagrams.
Introduction vii

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.

About This Book


This book assumes that you understand the C language and know how to compile
and link programs. If you have questions about these subj ects, consult your com­
piler documentation.

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:

• Chapter 1, "Using C Library Routines," gives general rules for understanding


and using C library routines and mentions special considerations that apply to
certain routines. It is recommended that you read this chapter before using the
run-time library; you may also want to tum to Chapter 1 when you have ques­
tions about library procedures.
• Chapter 2, "Run-Time Routines by Category," lists the C library routines by
category and discusses considerations that apply to each category. This chap­
ter makes it easy to locate routines by task. Once you find the routine you
want, tum to the reference page in Part 2 for a detailed description.
• Chapter 3, "Global Variables and Standard Types," describes variables and
types that are used by library routines. Global variables and standard types
are also described in the reference descriptions of the routines that use them.

Part 2, "Run-Time Functions," describes the library routines in alphabetical


order. Once you are familiar with the C library rules and procedures, you will
probably use this part most often.

Other Books of Interest


This book provides a guide to the C run-time library provided with the Microsoft
C Professional Development System version 6.0.
viii Microsoft C Run-Time Library Reference

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.

• Barkakati, Nabajyoti. The Waite Group's Microsoft C Bible. Indianapolis, IN:


Howard W. Sams, 1988.
A topical guide to the Microsoft C run-time library. A similar volume is avail­
able for the Microsoft QuickC® product.
• Campbell, Joe. C Programmer's Guide to Serial Communications. Indi­
anapolis, IN: Howard W. Sams & Company, 1987.
A comprehensive guide to the specialized area of serial communication pro­
gramming in C.
• Hansen, Augie. Proficient C: The Microsoft Guide to Intermediate & Ad­
vanced C Programming. Redmond, WA: Microsoft Press, 1987.
An intermediate-level guide to C programming.

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 .

An intennediate-level look at data structures using the C language.


• Plum, Thomas, and Jim Brodie. Efficient C. Cardiff, NJ: Plum Hall, 1985.
A guide to techniques for increasing the efficiency of C programs.
• Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vet­
terling. Numerical Recipes in C: The Art of Scientific Computing. New York:
Cambridge University Press, 1988.
A comprehensive look at numerical techniques using the C language.
• Schustack, Steve. Variations in C: Programming Techniques for Developing
Efficient Professional Applications. Redmond, WA: Microsoft Press, 1985.
An intennediate-level guide to developing business applications in C.
• Ward, Robert. Debugging C. Indianapolis, IN: Que Corporation, 1986.
An advanced guide to the theory and practice of debugging C programs.
• Wilton, Richard. Programmer's Guide to PC and PS/2 Video Systems:Maxi­
mum Video Pelformance from the EGA, VGA, HGC, & MCGA. Redmond,
WA: Microsoft Press, 1987.
An advanced guide to all the PC and PS/2 video modes.

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

Special Offer: Companion Disk


for Microsoft C Run-Time library Reference
Microsoft Press has created a companion disk for Microsoft C Run-Time Library
Reference. This disk, available in 5.25- and 3.5-inch format, contains nearly 300
example programs from the book. You can use code fragments from the compan­
ion disk for commercial or personal purposes without infringing on the copyright
of the book.

Domestic Ordering Information


To order, use the special reply card bound in the back of the book. If the card has
already been used, please send $19.95. (Please add applicable sales tax for the
following states: AZ, CA, CO, CT, DC, FL, GA, ID, IL, IN, KY, ME, MD, MA ,
MI, MN, NV, NJ, NY, NC, OH, SC, TN, TX, VA, WA. Microsoft reserves the
right to correct tax rates and/or collect the sales tax assessed by additional states
as required by law, without notice.) Please include $2.50 per disk set for domes­
tic postage and handling charges. Mail your order to: Microsoft Press, Attn: Com­
panion Disk Offer, 21919 20th Ave. SE, Box 3011, Bothell, WA 98041-3011.
Please specify 5.25-inch format or 3.5-inch format. Payment must be in U.S.
funds. You may pay by check or money order (payable to Microsoft Press) or by
American Express, VISA, or MasterCard. (If paying by credit card, please in­
clude both your card number and the expiration date.) Allow 2-3 weeks for
delivery upon receipt of your order by Microsoft.

Foreign Ordering Information (within the U.K., see below)


Follow ordering procedures for domestic ordering and add $6.00 for foreign post­
age and handling.

U.K. Ordering Information


Send your order in writing along with£18.95 (includes VAT) to: Microsoft
Press, 27 Wrights Lane, London W8 5TZ. You may pay by check or money
order (payable to Microsoft Press) or by American Express, VISA, MasterCard,
or Diners Club. (If paying by credit card, please include both your card number
and the expiration date.) Specify 5.25-inch format or 3.5-inch format.

Microsoft Press Companion Disk Guarantee


If the disk proves defective, send the defective disk along with your packing slip
(or copy) to: Microsoft Press, Consumer Sales, One Microsoft Way, Redmond,
WA 98052-6399.
xii Microsoft C Run-Time Library Reference

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.

The Companion Disk for Microsoft C Run-Time Library Reference is available


only from Microsoft Press.
PART1

Overview
Overview
The first part of this book provides an overview of the run-time
library provided with the Microsoft C Professional Development
System.

Chapter 1 is a general guide to the use of the run-time library


routines.

Chapter 2 lists the routines by category.

Chapter 3 tells how to access global variables and types defined


in the run-time library.
CHAPTER

Using C Library Routines

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.

1.1 Calling Library Routines


To use a C library routine, simply call it in your program, just as if it is defined
there. For instance, suppose you write the following program and name it
SAMPLE.C:

#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:

1. Header ("include") files that contain declarations and type definitions


required by library routines

2. Library files that contain the library routines in compiled form

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.

1.2 Using Header Files


As stated in the previous section, you should include C header files when using
library routines. This section describes particular reasons why header files are
required.
Using C Library Routines 7

1.2.1 Including Necessary Definitions


Many C library routines use constants, type definitions, or macros defined in a
header file. To use the routine, you must include the header file containing the
needed definition(s). The following list gives examples:

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

in the header file FCNTL.H.


uses constants such as 0 CREAT, which is defined

1}'pe definition Some library routines return a structure or take a:


structure as an argument. For example, stream
input/output routines use a structure of type FILE,
which is defined in STDIO.ff.

1.2.2 Including Function Declarations


The Microsoft C header files also contain function declarations for every func­
tion in the C library. These declarations are in the style recommended by the
ANSI C standard. Given these declarations, the compiler can perform "type
checking" on every reference to a library function, making sure that you have
used the correct return type and arguments. Function declarations are sometimes
called "prototypes," since the declaration serves as a prototype or template for
every subsequent reference to the function.

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 >:

you can later include the following declaration:

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.

1. 3 File Names and Path Names


Many library routines take strings representing paths and file names as argu­
ments. If you plan to transport your programs to the XENIX operating system,
you should remember that XENIX uses file- and path-name conventions that are
different from those used by DOS and OS/2. If you do not plan to transport your
programs to XENIX, you can skip this section.

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

1.4 Choosing Between Functions and Macros


This book uses the words "routine" and "function" interchangeably. However,
the term "routine" actually encompasses both functions and macros. Because
functions and macros have different properties, you should pay attention to
which form you are using. The descriptions in the reference section indicate
whether routines are implemented as functions or as macros.
Most routines in the Microsoft C library are functions. They consist of compiled
C code or assembled Microsoft Macro Assembler (MASM) code. However, a
few library routines are implemented as macros that behave like functions. You
can pass arguments to library macros and invoke them in the same way you in­
voke functions.
The main benefit of using macros is faster execution time. A macro is expanded
(replaced by its definition) during preprocessing, creating in-line code. Thus,
macros do not have the overhead associated with function calls. On the other
hand, each use of a macro inserts the same code in your program, whereas a func­
tion definition occurs only once regardless of how many times it is called. Func­
tions and macros thus offer a trade-off between speed and size.
Apart from speed and size issues, macros and functions have some other impor­
tant differences:

• 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 example increments a when passing it as an argument to the toupper


routine, which is implemented as a macro. It is defined in CTYPE.H:

/fd e f i n e t o u p p e r ( c ) ( ( i s l owe r ( c ) ) ? _t o u p p e r ( c ) : Cc> )

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 c l ude <ctype . h>

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

Since the macro definition no longer exists, subsequent references to toupper


use the function version.
A third way to make sure the compiler uses the function version is to declare the
function explicitly:

# 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.

1. 5 Stack Checking on Entry


For certain library routines, the compiler performs stack checking on entry. (The
"stack" is a memory area used for temporary storage.) Upon entry to such a
routine, the stack is checked to determine if it has enough room for the local vari­
ables used by that routine. If it does, space is allocated by adjusting the stack
pointer. Otherwise, a "stack overflow" run-time error occurs. If stack checking is
disabled, the compiler assumes there is enough stack space; if there is not, you
might overwrite memory locations in the data segment and receive no warning.
Typically, stack checking is enabled only for functions with large local-variable
requirements (more than about 1 50 bytes), since there is enough free space be­
tween the stack and data segments to handle functions with smaller requirements.
If the function is called many times, stack checking slows execution slightly.

Stack checking is enabled for the following library functions:

execvp scanf system


execvpe spawnvp vprintf
fprintf spawnvpe write
fscanf sprintf
printf sscanf
Using C Library Routines 13

1.6 Handling Errors


Many library routines return a value that indicates an error condition. To avoid
unexpected results, your code should always check such error values and handle
all of the possible error conditions. The description of each library routine in the
reference section lists the routine's return value(s).
Some library functions do not have a set error return. These include functions
that return nothing and functions whose range of return values makes it im­
possible to return a unique error value. To aid in error handling, some functions
in this category set the value of a global variable named errno.
If the reference description of a routine states that it sets the errno variable, you
can use errno in two ways:

1. Compare errno to the values defined in the header file ERRNO.H.


2. Handle errno with the perror or strerror library routines. The perror
routine prints a system error message to the standard error (stderr). The
strerror routine stores the same infonnation in a string for later use.

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

matherr reference description.


it matherr or matherrl. Your routine must follow the rules listed in the

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

• No floating-point arguments are given in the call to printf.


• No floating-point values are used elsewhere in the program.

As a result, the following error occurs:

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 } ;
}

1.9 Using Huge Arrays with library Functions


In programs that use small, compact, medium, and large memory models, Micro­
soft C allows you to use arrays exceeding the 64K (kilobyte) limit of physical
memory in these models by explicitly declaring the arrays as _huge. However,
generally, you cannot pass _huge data items as arguments to C library functions.
In the compact-model library used by compact-model programs and in the large­
model library used by both large-model and huge-model programs, only the func­
tions listed below use argument arithmetic that works with _huge items:
bsearch fmemchr fmemmove ltind
fread )memcmp -fmemset lsearch
fwrite _fmemcpy iialloc memccpy
_fmemccpy _fmemicmp hfree memchr
Using C Library Routines 17

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.)

2.2 Character Classification and Conversion


The character classification and conversion routines allow you to test individual
characters in a variety of ways and to convert between uppercase and lowercase
characters.

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

The classification routines identify characters by finding them in a table of classi­


fication codes. Using these routines to classify characters is generally faster than
writing a test expression such as the following:
i f ( ( c >= 0 ) II c <= 0 x 7 f l )

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.

2.3 Data Conversion


The data-conversion routines convert numbers to strings of ASCII characters
and vice versa. These routines are implemented as functions, all of which are de­
clared in the include file STDLIB.H. The atof function, which converts a string
to a floating-point value, is also declared in MATH.H.

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

strtol Converts string to a long integer


_strtold Converts string to long double
strtoul Converts string to an unsigned long integer
ultoa Converts unsigned long to string

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

The access, chmod, _fullpath, _makepath, remove, rename, _splitpath, stat,


and unlink routines operate on files specified by a path name or file name.
The chsize, filelength, fstat, isatty, locking, and setmode routines work with
files designated by a file handle.
The mktemp and umask routines have functions that are slightly different from
the other routines. The mktemp routine creates a unique file name, and the pro­
grammer can use mktemp to create unique file names that do not conflict with
the names of existing files. The umask routine sets the default permission mask
for any new files created in a program. The mask can override the permission set­
ting given in the open or creat call for the new file.
Run-Time Routines by Category 25

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.

2. 6. 1 Lo w-Le vel Graphics and Character-Font Functions


The low-level graphics and font functions are declared in the include file
GRAPH.H.
The library can be divided into the eight categories listed below, which corre­
spond to the different tasks involved in creating and manipulating graphic objects.
Most graphics routines work only in DOS. Two categories of routines ("configur­
ing mode and environment" and "creating text output") work in OS/2 as well
as DOS.

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™

The following sections explain each of these categories.


26 Microsoft C Run-Time Library Reference

2. 6. 1. 1 Configuring Mode and Environment


Routines that configure the mode and environment establish the graphics or text
mode of operation, determine the current graphics environment, and control the
display of the cursor.
All of the routines listed in this section are available in OS/2 as well as DOS.

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

2. 6. 1.2 Setting Coordinates


The "set coordinates" routines set the current text or graphics position and con­
vert pixel coordinates between the various graphic coordinate systems.
The Microsoft C graphics functions recognize three sets of coordinates:

I. Fixed physical coordinates


2. View coordinates defined by the application
3. Window coordinates that can include floating-point values
Run-Time Routines by Category 27

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

_getcurrentposition_w Determines current position in window coordinates

_getphyscoord Converts view coordinates to physical coordinates

_getviewcoord Converts physical coordinates to view coordinates

_getviewcoord_w Converts window coordinates to view coordinates

_getviewcoord_wxy Converts window coordinates in _wxycoord struc­


ture to view coordinates

_getwindowcoord Converts view coordinates to window coordinates

_setcliprgn Limits graphic output to a region of the screen

_setvieworg Positions the view-coordinate origin

_setviewport Limits graphics output to a region of the screen and


positions the view-coordinate origin to the upper-left
corner of that region

setwindow Defines a floating-point window coordinate system

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 _getcurrentposition and _getcurrentposition_w routines allow you to de­


termine the location of the current graphics-output point.
28 Microsoft C Run-Time Library Reference

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 physical coordinates of any view-coordinate point can be determined with


the _getphyscoord function, and the view coordinates of any physical point can
be determined with the _getviewcoord function.

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.

The _setwindow function defines the current viewport as a real-coordinate win­


dow bound by the specified floating-point values.

2. 6. 1.3 Setting low-level Graphics Palettes


Use the low-level palette routines to select or remap color palettes.

Routine Use
_remapallpalette Changes all color indexes in the current palette

_remappalette Changes a single color index in the current palette

_selectpalette Selects a predefined 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.

The _remappalette routine changes a single color index to a specified color


value. The _remapallpalette routine changes all of the available palette entries
simultaneously.

2. 6. 1.4 Setting Attributes


The low-level output functions that draw lines, arcs, ellipses, and other basic
figures do not specify color or line-style information. Instead, the low-level
Run-Time Routines by Category 29

graphics functions rely on a set of attributes that are set independently by the fol­
lowing functions:

Routine Use

_getarcinfo Determines the endpoints in viewport coordinates of


the most recently drawn arc or pie

_getcolor Gets the current color

_getfillmask Gets the current fill mask

_getlinestyle Gets the current line-style mask

_getwritemode Gets the current logical write mode

setcolor Sets the current color

setfillmask Sets the current fill mask

_setlinestyle Sets the current line-style mask

setwritemode Sets logical write mode for line drawing

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.

2. 6. 1 . 5 Creating Graphics Output


The graphics output functions use a set of specified coordinates and draw various
figures. They use the current or default attributes for line-style mask, fill mask,
write mode, background color, and foreground color.
30 Microsoft C Run· Time Library Reference

The name of each function announces its task or the figure it draws, as the follow­
ing list indicates:

Routine Use

_arc, _arc_w, _arc_wxy Draw an arc

_ellipse, _ellipse_w, Draw an ellipse or circle


_ellipse_wxy

_floodfill, _floodfill_w Flood-fill an area of the screen with


the current color

_getcurrentposition, Obtain the current graphic-output


_getcurrentposition_w position used by _lineto and
_outgtext

_getpixel, _getpixel_w Obtain a pixel 's color

_lineto, _lineto_w Draw a line from the current graphic


output position to a specified point

_moveto, _moveto_w Move the current graphic-output posi­


tion to a specified point

_pie, _pie_w, _pie_wxy Draw a pie-slice-shaped figure

_polygon, _polygon_w, Draw or scan-fill a polygon


_polygon_wxy

_rectangle, _rectangle_w,
_rectangle_wxy
Draw L scan-fill a rectangle

_setpixel, _setpixel_w Set a pixel 's color

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­
_

fine the coordinates and use the window coordinate system.

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.

2. 6. 1. 6 Creating Text Output


The next group of routines provides text output in both graphics and text modes.
Unlike the standard console 1/0 library routines, these functions recognize text­
window boundaries and use the current text color.
Run-Time Routines by Category 31

All of the routines listed in this section work in OS/2 as well as DOS.

Routine Use

_displaycursor Sets the cursor on or off upon exit from a graphics


routine

_gettextcolor Obtains the current text color

_gettextcursor Returns the current cursor attribute (text modes only)


_gettextposition Obtains the current text-output position
_gettextwindow Gets the current text window boundaries

outmem Prints text of a specified length from a memory


buffer

outtext Outputs a text string to the screen at the current text


position

_scrolltextwindow Scrolls the current text window up or down

settextcolor Sets the current text color

settextcursor Sets the current cursor attribute (text modes only)

_settextposition Relocates the current text position

settextwindow Defines the current text-display window

_wrapon Enables or disables line wrap

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

_getimage, Store a screen image in memory


_getimage_w,
_getimage_wxy

_i magesize, Return the size (in bytes) of the buffer needed to


_imagesize_w, store the image
_imagesize_wxy

_putimage, Retrieve an image from memory and display it


_putimage_w

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

_getfontinfo Obtains the current font characteristics

_getgtextextent Determines the width in pixels of specified text in


the current font

_getgtextvector Gets orientation of font text output

_outgtext Outputs text in the current font to the screen at the


specified pixel position

_registerfonts Initializes font library

setfont Finds a single font that matches a specified set of


characteristics and makes this font the current font
for use by the _outgtext function
_setgtextvector Sets the current orientation for font text output
_unregisterfonts Frees memory allocated by _registerfonts

2. 6.2 Presentation-Graphics Functions


The presentation-graphics functions are declared in the PGCHART.H include
file. The library can be divided into the three categories listed below, correspond­
ing to the different tasks involved in creating and manipulating graphic objects:
Run-Time Routines by Category 33

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

Manipulating Modify basic chart structures (e.g., palettes, cross­


presentation-graphics hatching styles).
structures

2. 6.2. 1 Displaying Presentation Graphics


The functions listed in this section initialize the presentation-graphics library and
display the specified graph type.

Because the _pg_initchart routine initializes the presentation-graphics library, it


must be called before any other function in the presentation-graphics library. The
_pg_defaultchart function initializes the variables in the chart environment.
The other routines in this category display the specified graph. The single-series
versions plot one set of data, and the multiseries versions (those ending with an
ms suffix) plot several sets of data in the same chart style.
Presentation-graphics programs can display text in different font sizes by taking
advantage of font-based characters (see Section 2.6. 1 .8, "Displaying Fonts.")
Call the _registerfonts and _setfont routines to select a font before calling the
_pginitchart routine. Subsequent charts use the selected font. You can later call
the _unregisterfonts routine to restore the default character font and free the
memory previously allocated for fonts.

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

2. 6.2.2 Analyzing Presentation-Graphics Charts


These routines calculate default values for the specified graph type but do not dis­
play the chart. The single-series versions analyze one set of data, and the multi­
series versions analyze several sets of data in the same chart style.

Routine Use
_pg_analyzechart Analyzes a single series of data for a bar, column, or
line chart

_pg_analyzechartms Analyzes a multiseries of data for a bar, column, or


line chart

_pg_analyzepie Analyzes data for a pie chart

_pg_analyzescatter Analyzes a single series of data for a scatter diagram


_pg_analyzescatterms Analyzes a multiseries of data for a scatter diagram

2. 6.2. 3 Manipulating Presentation-Graphics Structures


These functions control low-level aspects of the presentation-graphics package.

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

_pg_getstyleset Retrieves the contents of the current sty leset


_pg_setstyleset Sets the contents of the current styleset
_pg_resetstyleset Resets the contents of the current styleset to the de­
fault value for the current screen mode
_pg_getchardef Retrieves the current 8-by-8-pixel bit map for a
specified character
_pg_setchardef Sets the 8-by-8-pixel bit map for a specified
character
Run-Time Routines by Category 35

2. 7 Input and Output


The input and output (1/0) routines of the standard C library allow you to read
and write data to and from files and devices. In C, there are no predefined file
structures; all data items are treated as sequences of bytes. The following three
types of 1/0 functions are available:

I. Stream

2. Low-level

3. Console and port

The "stream" 1/0 functions treat data as a stream of individual characters. By


choosing among the many stream functions available, you can process data in
different sizes and formats, from single characters to large data structures. Stream
1/0 also provides buffering, which can significantly improve performance.
The "low-level" 1/0 routines do not perform buffering and formatt i ng. Instead,
they invoke the operating system's input and output capabilities directly. These ·
routines let you access files and peripheral devices at a more basic level than the
stream functions.

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.

2. 7. 1 Text and Binary Modes


Many C programs use data files for input and output. Under DOS and OS/2, data
files are normally processed in text mode. In this mode, each carriage-retum-line­
feed (CR-LF) combination is translated into a single line-feed character during
36 Microsoft C Run- Time Library Reference

input. During output, each line-feed character is translated into a CR-LF


combination.

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.

You can change the value of _fmode in two ways:

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.

2. 7.2 Stream Routines


Stream 1/0 functions handle data as a continuous stream of characters. To
use the stream functions, you must include the file STDIO.H in your program.
This file defines constants, types, and structures used in the stream functions,
and contains function declarations and macro definitions for the stream
routines.
Run-Time Routines by Category 37

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.

Some of the constants defined in STDIO.H n\ ay be useful in your program. The


manifest constant EOF is defined to be the value returned at end-of-file. NULL is
the null pointer. FILE is the structure that maintains information about a stream.
BUFSIZ defines the default size of stream buffers, in bytes.

Routine Use
clearerr Clears the error indicator for a stream

fclose Closes a stream

fcloseall Closes all open streams

fdopen Associates a stream with an open file handle

feof Tests for end-of-file on a stream

. ferror Tests for error on a stream


mush Flushes a stream

fgetc Reads a character from a stream (function version)

fgetchar Reads a character from stdio (function version)


fgetpos Gets the position indicator of a stream

fgets Reads a string from a stream


fileno Gets the file handle associated with a stream

flushall Flushes all streams


fopen Opens a stream
38 Microsoft C Run-Time Library Reference

fprintf Writes formatted data to a stream

fputc Writes a character to a stream (function version)

fputchar Writes a character to stdout (function version)


fputs Writes a string to a stream

fread Reads. unformatted data from a stream

freopen Reassigns a FILE pointer to a new file

fscanf Reads formatted data from a stream


fseek Moves file position to a given location

fsetpos Sets the position indicator of a stream

_fsopen Opens a stream with file sharing

ftell Gets current file position


fwrite Writes unformatted data items to a stream

getc Reads a character from a stream

getchar Reads a character from stdio

gets Reads a line from stdio

getw Reads a binary int item from a stream

printf Writes formatted data to stdout

putc Writes a character to a stream

putchar Writes a character to stdout

puts Writes a line to a stream

putw Writes a binary int item to a stream

rewind Moves file position to beginning of a stream


rmtmp Removes temporary files created by tmpfile
scanf Reads formatted data from stdio
setbuf Controls stream buffering
setvbuf Controls stream buffering and buffer size
sprintf Writes formatted data to a string
sscanf Reads formatted data from a string
tempnam Generates a temporary file name in given directory
Run-Time Routines by Category 39

tmptile Creates a temporary file


tmpnam Generates a temporary file name

ungetc Places a character in the buffer


vfprintf Writes formatted data to a stream
vprintf Writes formatted data to stdout

vsprintf Writes formatted data to a string

2. 7.2. 1 Opening a Stream


A stream must be opened using the fdopen, fopen, freopen, or _fsopen function
before input and output can be performed on that stream. When opening a
stream, the named stream can be opened for reading, writing, or both, and can be
opened in either text or binary mode.

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.

2. 7.2.2 Using Predefined Stream Pointers


When a program begins execution, the C start-up code automatically opens
several streams: standard input, standard output, and standard error. By default,
the standard input, standard output, and standard error streams are directed to the
console (keyboard and screen). This means that when a program expects input
from the "standard input," it receives that input from the console. Similarly, a
program that writes to the "standard output" prints its data to the console. Error
messages generated by the library routines are sent to the "standard error," mean­
ing that error messages appear on the user's console.
Under DOS, two additional streams are opened: standard auxiliary and standard
print. (These streams are not available in OS/2.) The assignment of standard
auxiliary and standard print depends on the machine configuration. These
streams usually refer to the first serial port and a printer port, but those ports may
not be available on some systems. Be sure to check your machine configuration
before using these streams.

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

stdout Standard output

stderr Standard error

stdaux Standard auxiliary (DOS only)

stdprn Standard print (DOS only)

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.

2. 7.2.3 Controlling Stream Buffering


As mentioned earlier, stream routines can use in-memory buffers to speed 1/0
operations. Files opened using the stream routines are buffered by default, except
for stdaux and stdprn, which are normally unbuffered. The stdout and stderr
streams are flushed whenever they are full or (if you are writing to a character
device) after each library call.

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

2. 7.2.4 Closing Streams


The fclose and fcloseall functions close a stream or streams. The fclose routine
closes a single specified stream; . fcloseall closes all open streams except stdin,
stdout, stderr, stdaux, and stdprn. If your program does not explicitly close a
stream, the stream is automatically closed when the program terminates. How­
ever, it is a good practice to close a stream when your program is finished with it,
as the number of streams that can be open at a given time is limited.

2. 7.2. 5 Reading and Writing Data


The stream functions allow you to transfer data in a variety of ways. You can
read and write binary data (a sequence of bytes), or specify reading and writing
by characters, lines, or more complicated formats.

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.2. 6 Detecting Errors


When an error occurs in a stream operation, an error indicator for the stream is
set. You can use the ferror macro to test the error indicator and determine
whether an error has occurred. Once an error has occurred, the error indicator for
the stream remains set until the stream is closed, or until you explicitly clear the
error indicator by calling clearerr or rewind.
42 Microsoft C Run· Time Library Reference

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

2. 7.3. 1 Opening a File


You must open a file before perfonning I/0 functions on it. The open function
opens a file; it can also create the file when opening it. In OS/2 and DOS ver­
sions 3.0 and later, you can use sopen to open a file with file-sharing attributes.
The creat function can create and open a file.
The file can be opened for reading, writing, or both, and opened in either text or
binary mode (see Section 2.7. l , "Text and Binary Modes"). The include file
FCNTL.H must be included when opening a file, as it contains definitions for
flags used in open. In some cases, the files SYS\TYPES.H and SYS\STAT.H
must also be included; for more infonnation, see the reference description for the
open function.
These functions return a file handle, which is nonnally assigned to an integer
variable. You use the variable to refer to the opened file.
Run-Time Routines by Category 43

2. 7.3.2 Reading and Writing Data


Use the read and write routines to read and write to files. These operations begin
at the current position in the file. The current position is updated each time a read
or write operation occurs.
The lseek function allows you to place the file pointer anywhere in the file. The
next operation occurs at the position you specified. The tell function indicates the
current position of the file pointer. The eof routine tests for the end of the file.
Low-level 1/0 routines set the errno variable when an error occurs. Chapter 3,
"Global Variables and Standard Types," describes errno.
Character-oriented devices, such as the console, do not have file pointers. The
lseek and tell routines have undefined results if used on a handle associated with
a device.

2. 7. 3.3 Closing Files


The close function closes an open file. Open files are automatically closed when
a program terminates. However, it is a good practice to close a file when your
program is finished with it, as there is a limit to the number of files that can be
open at one time.

2. 7. 3. 4 Using Predefined Handles


When a program begins execution, three files are automatically opened: standard
input, standard output, and standard error. In DOS, two additional files are
opened: standard auxiliary and standard print. (These files are not available in
OS/2.)
Low-level routines can access these files using the following predefined handles:

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.

2. 7. 4 Console and Port 1/0


The console and port 1/0 routines are implemented as functions and are declared
in the include file CONIO.H. These functions perform reading and writing opera­
tions on your console or on the specified port. The cgets, cscanf, getch, getche,
and kbhit routines take input from the console, while cprintf, cputs, putch, and
ungetch write to the console. The input or output of these functions can be
redirected.

Routine Use
cgets Reads a string from the console
cprintf Writes formatted data to the console

cputs Writes a string to the console


cscanf Reads formatted data from the console
getch Reads a character from the console
getche Reads a character from the console and echoes it
inp Reads one byte from the specified 1/0 port
inpw Reads a two-byte word from the specified 1/0 port
kbhit Checks for a keystroke at the console
outp Writes one byte to the specified 1/0 port
outpw Writes a two-byte word to the specified 1/0 port
putch Writes a character to the console
ungetch "Ungets" the last character read from the console so
that it becomes the next character read

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
_ _

Section 2. 14, "System Calls. "

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

fieeetomsbin Converts IEEE single-precision number to Microsoft


binary format

floor, floorl Find the largest integer less than or equal to the
argument

fmod, fmodl Find the floating-point remainder

fmsbintoieee Converts Microsoft binary single-precision number


to IEEE format

_fpreset Reinitializes the floating-point-math package

frexp, frexpl Calculate an exponential value

hypot, hypotl Calculate the hypotenuse of right triangle


2exp
ldexp, ldexpl Calculate the product of the argument and

I div Divides one long integer by another, returning the


quotient and remainder

log, logl Calculate the natural logarithm

loglO, IoglOI Calculate the base- I 0 logarithm

_Irotl, _Irotr Shift an unsigned long int item left ( _lrotl) or right
( _lrotr)

matherr, _matherrl Handle math errors

max, min Return the larger or smaller of two values

modf, modfl Break down the argument into integer and fractional
parts

pow, powl Calculate a value raised to a power

rand Gets a pseudorandom number

_rotl, _rotr Shift an unsigned int item left ( _rotl) or right


( _rotr)

sin, sinl Calculate the sine

sinh, sinhl Calculate the hyperbolic sine

sqrt, sqrtl Find the square root

srand Initializes a pseudorandom series

status87 Gets the floating-point status word

tan, tanl Calculate the tangent

tanh, tanhl Calculate the hyperbolic tangent


48 Microsoft C Run-Time Library Reference

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

_bfreeseg Frees a based heap

_bheapseg Allocates a based heap

calloc, _bcalloc, _fcalloc , _ncalloc Allocate storage for an array

_expand , _bexpand , _fexpand , Expand or shrink a block of memory


_nexpand without moving its location

free, _bfree, _ffree, _nfree Free an allocated block

_freed Returns approximate number of items


of given size that could be allocated
in the near heap

halloc Allocates storage for huge array


_heapadd, _bheapadd Add memory to a heap

_heapchk, _bheapchk, _tbeapchk, Check a heap for consistency


_nheapchk
_heapmin, _bheapmin, Release unused memory in a heap
_theapmin, _nheapmin
Run-Time Routines by Category 49

_heapset, _bheapset, _tbeapset, Fill free heap entries with a specified


_nheapset value

_heapwalk, _bheapwalk, Return information about each entry


_tbeapwalk, _nheapwalk in a heap

hfree Frees a block allocated by halloc

_nmalloe
malloc, bmalloc, -fmalloc, Allocate a block of memory

_memavl Returns approximate number of bytes


available for allocation in the near
heap

_memmax Returns size of largest contiguous


free block in the near heap

_msize, · _bmsize, _fmsize, Return size of an allocated block


_nmsize

_nrealloe
realloc, brealloc, -frealloc, Reallocate a block to a new size

stackavail Returns size of stack space available


for allocation with alloca

Some memory-management routines, such as malloc, are available in different


versions that begin with _b, _f, or _n. These variations are described in the fol­
lowing section.

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.

2. 10. 1 Near and Far Heaps


As mentioned in the previous section, heap memory can reside inside or outside
your program 's default data segment, depending on what memory model your
program uses. When it lies inside the default data segment, the heap is called the
"near heap," since it can be accessed with near pointers. The "far heap" is
memory that spans one or more segments outside the default data segment. The
far heap can be accessed only with far pointers.
In various memory models, malloc automatically allocates memory from the
near heap or far heap, as appropriate. The C library also includes near and far ver­
sions of malloc, free, and other memory-management routines, which allow you
to specify the near and far heaps explicitly. These have the same names as stand­
ard memory routines, but are preceded by _n (for near) or _f (for far).
For instance, the _nmalloc routine always allocates memory from the near heap
and returns a near pointer, no matter which memory model your program uses.
Use _nfree to release memory allocated with _nmalloc.
Similarly, _fmalloc always allocates memory from the far heap and returns a far
pointer, regardless of memory model. Use the _tTree routine to release memory
·

allocated with fmalloc.

2. 10.2 Based Heaps


You can also allocate memory from a "based heap," which is a single segment
that lies outside the default data segment. Based-heap routines generally use the
same names as standard memory routines, but begin with _b. For instance,
_bmalloc allocates a memory block from the based heap and _bfree frees the
block.
Based heaps offer the following advantages:

• 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

as many based-heap segments as needed (within the confines of available


memory).

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.

2. 1 1 Process and Environment Control


The process-control routines allow you to start, stop, and manage processes from
within a program. Environment-control routines allow you to get and change in­
formation about the operating-system environment.

A "process" is a program being executed by the operating system. It consists of


the program's code and data, plus information about the process, such as the num­
ber of open files. Whenever you execute a program at the operating-system level,
you start a process.

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

abort Aborts a process without flushing buffers or calling


functions registered by atexit and onexit

assert Tests for logic error

atexit Schedules routines for execution at program


termination

_beginthread Creates an execution thread (OS/2 only)

cexit Performs the exit termination procedures (such as


flushing buffers) and returns control to the calling
program

turns control to the calling program


c exit Performs the exit termination procedures and re­

cwait Suspends the calling process until a specified child


process terminates (OS/2 only)

endthread Terminates an execution thread (OS/2 only)


52 Microsoft C Run-Time Library Reference

exeel Executes child process with argument list

execle Executes child process with argument list and given


environment

execlp Executes child process using PATH variable and ar­


gument list

execlpe Executes child process using PATH variable, given


environment, and argument list

execv Executes child process with argument array

execve Executes child process with argument array and


given environment

execvp Executes child process using PATH variable and ar­


gument array

execvpe Executes child process using PATH variable, given


environment, and argument array

exit Calls functions registered by atexit and onexit, then


flushes all buffers and closes all open files before ter­
minating the process

exit Terminates process without processing atexit or


onexit functions or flushing buffers

getenv Gets the value of an environment variable

getpid Gets process ID number

longj mp Restores a saved stack environment

onexit Schedules routines for execution at program


termination

_pclose Waits for a child command and closes a pipe on the


associated stream

perror Prints error message

_pipe Creates a pipe

_popen Creates a pipe and asynchronously executes a child


copy of the command processor

putenv Adds or changes the value of an environment


variable

raise Sends a signal to the calling process

setjmp Saves a stack environment


Run-Time Routines by Category 53

signal Handles an interrupt signal


spawnl Executes child process with argument list
spawnle Executes child process with argument list and given
environment
spawnlp Executes child process using PATH variable and ar­
gument list
spawnlpe Executes child process using PATH variable, given
environment, and argument list
spawnv Executes child process with argument array
spawnve Executes child process with argument array and
given environment
spawnvp Executes child process using PATH variable and ar­
gument array
spawnvpe Executes child process using PATH variable, given
environment, and argument array
system Executes an operating system command
wait Suspends the calling process until any of the caller's
immediate child processes terminate (OS/2 only)

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.

Several process-control routines take advantage of the multitasking capability of


OS/2. The _beginthread and _endthread routines create and tenninate execu­
tion threads. The cwait and wait routines suspend the calling process until one
child process tenninates. The _pipe, _popen, and _pclose routines create and
manipulate pipes, which link processes for sequential execution.

Table 2.1 Forms of the spawn and exec Routines

Argument-Passing
Routines Locating the File Convention Environment Settings

execl, spawnl Do not use PATH Argument list Inherited from parent

execle, spawnle Do not use PATH Argument list Pointer to environ­


ment table for child
process passed as last
argument

execlp, spawnlp Use PATH Argument list Inherited from parent

execlpe, spawnlpe Use PATH Argument list Pointer to environ­


ment table for child
process passed as last
argument

execv, spawnv Do not use PATH Argument array Inherited from parent

execve, spawnve Do not use PATH Argument array Pointer to environ­


ment table for child
process passed as last
argument

execvp, spawnvp Use PATH Argument array Inherited from parent

execvpe, spawnvpe Use PATH Argument array Pointer to environ­


ment table for child
process passed as last
argument
Run-Time Routines by Category 55

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.

2. 12 Searching and Sorting


Search and sort routines provide binary-search, linear-search, and quick-sort
capabilities. They are all declared in SEARCH.H.

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.

Routines beginning with _f are model-independent versions of the corresponding


routines and are useful in mixed-model programs. These routines can be called
from any point in the program, regardless of which model is being used.

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

strerror Maps a user-defined error message to a string

stricmp, _fstricmp Compare two strings without regard to case

strlen, _fstrlen Find length of string

strlwr, _fstrlwr Convert string to lowercase

strncat, _fstrncat Append characters of a string

strncmp, _fstrncmp Compare characters of two strings

strncpy, _fstrncpy Copy characters of one string to another

strnicmp, _fstrnicmp Compare characters of two strings without regard


to case

strnset, _fstrnset Set characters of a string to a given character

strpbrk, _fstrpbrk Find first occurrence of a character from one string


in another

strrchr, _fstrrchr Find last occurrence of a given character in string

strrev, _fstrrev Reverse string

strset, _fstrset Set all characters of a string to a given character

strspn, _fstrspn Find first substring from a given character set in a


string

strstr, _fstrstr Find first occurrence of a given string in another


string

strtok, _fstrtok Find next token in a string

strupr, _fstrupr Convert a string to uppercase

All string functions work on null-terminated character strings. When working


with character arrays that do not end with a null character, you can use the buffer­
manipulation routines, described in Section 2. 1 .

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

2. 14. 1 BIOS Interface


The functions in this category provide direct access to the BIOS interrupt ser­
vices. They are all declared in BIOS.ff.

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

_bios_timeofday Provides access to system clock, using INT O x IA

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 creatnew Creates a new file and returns an error if a file


having the same name exists, using DOS system
call Ox5B

dos tindfirst Finds first occurrence of a given file, using DOS sys­
tem call Ox4E

_dos_tindnext Finds subsequent occurrences of a given file, using


DOS system call Ox4F

dos freemem Frees a block of memory, using DOS system


call Ox49

_dos_getdate Gets the system date, using DOS system call Ox2A

_dos_getdiskfree Gets information on a disk volume, using DOS sys­


tem call Ox36

_dos_getdrive Gets the current default drive, using DOS system


call Ox 19

_dos_gettileattr Gets current attributes of a file or directory, using


DOS system call Ox43

_dos_getftime Gets the date and time a file was last written, using
DOS system call Ox57

_dos_gettime Gets the current system time, using DOS system


call Ox2C

_dos_getvect Gets the current value of a specified interrupt vector,


using DOS system call Ox35

_dos_keep Installs terminate-and-stay-resident (TSR) programs


using DOS system call Ox3 l

_dos_open Opens an existing file, using DOS system call Ox3D

dos read Reads a file, using DOS system call Ox3F

_dos_setblock Changes the size of a previously allocated block,


using DOS system call Ox4A

_dos_setdate Sets the current system date, using DOS system


call Ox2B

_dos_setdrive Sets the default disk drive, using DOS system


call OxOE

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

_dos_setvect Sets a new value for the specified interrupt vector,


using DOS system call Ox25

_dos_write Sends output to a file, using DOS system call Ox40

dosexterr Obtains in-depth error information from DOS sys­


tem call Ox59

_enable Enables interrupts

FP_OFF Returns offset portion of a far pointer (OS/2


and DOS)

FP_SEG Returns segment portion of a far pointer (OS/2


and DOS)

_hanlerr Establishes a hardware error handler

_hardresume Returns to DOS after a hardware error

_hardretn Returns to the application after a hardware error

int86 Invokes DOS interrupts

int86x Invokes DOS interrupts with segment register values

intdos Invokes DOS system call using registers other than


DX and AL

intdosx Invokes DOS system call using registers other than


DX and AL with segment register values

segread Returns current values of segment registers (OS/2


and DOS)

The _harderr routine is used to define a hardware-error interrupt handler. The

to define the returnfrom the error.


hardresume and hardretn routines are used within a hardware error handler

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

difftime Computes the difference between two times

ftime Puts current system time in variable of type


struct tm
gmtime Converts time from integer to struct tm

localtime Converts time from integer to struct tm with local


correction

mktime Converts time to a calendar value

_strdate Returns the current system date as a .string


strftime Formats a date and time string
strtime Returns the current system time as a string

time Gets current system time as a long integer

tzset Sets external time variables from the environment


time variable

utime Sets file-modification time

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

2. 16 Variable-Length Argument Lists


The va_arg, va_end, and va_start routines are macros that provide a portable
way to access the arguments to a function when the function takes a variable
number of arguments. Two versions of the macros are available: the macros de­
fined in the V ARARG.H include file, which are compatible with the UNIX Sys­
tem V definition, and the macros defined in STDARG.H, which conform to the
ANSI C standard.

Routine Use
va_arg Retrieves argument from list

va_end Resets pointer


va start Sets pointer to beginning of argument 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

The Microsoft C Run-Time Library contains definitions for a number of varia­


bles and standard types used by library routines. You can access these variables
and types by including in your program the files in which they are declared, or by
giving appropriate declarations in your program, as shown in the following
sections.

3. 1 _amblksiz
The _amblksiz variable controls memory heap granularity.

It is declared in the MALLOC.H include file as follows:


extern unsigned int _amblksiz;

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).

3.2 daylight, timezone, tzname


The daylight, timezone, and tzname variables are global timezone variables
used in time functions.

They are declared in the TIME.H include files as follows:


extern int daylight;

extern long timezone;

extern char *tzname [2];

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.

timezone Difference in seconds between Greenwich mean


time and the local time. Default value is 28,800.
tzname[O] Three-letter time zone name derived from the TZ en­
vironment variable. Default value is "PST" (Pacific
standard time).
tzname[l] Three-letter daylight-saving-time zone name derived
from the TZ environment variable. Default value is
PDT. If the DST zone is omitted from TZ,
tzname[l] is an empty string.
Global Variables and Standard Types 65

3.3 _doserrno, errno, sys_errlist, sys_nerr


The _doserrno, errno, sys_errlist, and sys_nerr variables contain error codes,
and are used by the perror and _strerror routines to print error infonnation.

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;

extern int errno;

extern char *sys_errlist[ ];

extern int sys_nerr;


The errno variable is set to an integer value to reflect the type of error that has
occurred in a system-level call. Each errno value is associated with an error mes­
sage, which can be printed with the perror routine or stored in a string with the
strerror routine.
Note that only some routines set the errno variable. If a routine sets errno, the
description of the routine in the reference section says so explicitly.
The value of errno reflects the error value for the last call that set errno. How­
ever, this value is not necessarily reset by later successful calls. To avoid confu­
sion, test for errors immediately after a call.

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.

Table 3.l errno Values and Their Meanings

Constant Meaning Value

ElBIG Argument list too long 7

EACCES Pennission denied 13


EBADF Bad file number 9

EDEADLOCK Resource deadlock would occur 36

EDOM Math argument 33

EEXIST File exists 17

EINVAL Invalid argument 22


EMFILE Too many open files 24
ENOENT No such file or directory 2
ENOEXEC Exec format error 8
ENOMEM Not enough memory 12
ENOSPC No space left on device 28
ERANGE Result too large 34

EXDEV Cross-device link 18

3. 4 _fmode
The fmode variable controls the default file-translation mode.

It is declared in the STDLIB.H include file as follows:

extern int _fmode;

By default, the value of _fmode is O_TEXT, causing files to be translated in


text mode (unless specifically opened or set to binary mode). When _fmode is
set to O_BINARY, the default mode is binary. You can set _fmode to the flag
O_BINARY by linking with BINMODE.OBJ or by assigning it the 0_BINARY
value.
Global Variables and Standard Types 67

3. 5 _osmajor, _osminor, _osmode, _osversion


The _osmajor, _osminor, _osmode, and _osversion variables specify the ver­
sion number of the operating system or the current mode of operation.

They are declared in the STDLIB.H include file as follows:

extern unsigned char _osmajor;

extern unsigned char _osminor;

extern unsigned char _osmode;

extern unsigned char _osversion;


The _osmajor, _osminor, and _osversion variables specify the version number
of DOS or OS/2 currently in use. The _osmajor variable holds the "major'' ver­
sion number and the osminor variable stores the "minor" version number.
Thus, under DOS vers ion 3.20, _osmajor is 3 and _osminor is 20. The
_osversion variable holds both values; its low byte contains the major version
number and its high byte the minor version number.

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.

It is declared in the STDLIB.H include file as follows:

extern char *environ [ ] ;


The environ variable provides access to memory areas containing process­
specific information.
68 Microsoft C Run-Time Library Reference

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.

Standard Type Description


clock_t The clock_t type, defined in TIME.H, stores time
values. It is used by the clock function.
r
complex The complex structure, defined in MATH.H, stores
the real and imaginary parts of complex numbers. It
is used by the cabs function.
Global Variables and Standard Types 69

diskfree_t The diskfree t structure, defined in DOS.H, stores


disk information used by the _dos__getdiskfree
routine.
diskinfo t The diskinfo t structure, defined in BIOS.ff, re­
cords information about disk drives returned by the
_bios_disk routine.
div_t, ldiv_t The div t and ldiv t structures, defined in
STDLffi.H, store the values returned by the div and
ldiv functions, respectively.
dosdate t The dosdate t structure, defined in DOS.H, records
the current system date used in the _dos__getdate
and dos setdate routines.
dostime_t The dostime t structure, defined in DOS.H, records
the current system time used in the _dos__gettime
and _dos_settime routines.
DOS ERROR The DOSERROR structure, defined in DOS.H,
stores values returned by DOS system call 59H
(available under DOS versions 3.0 and later).
exception The exception structure, defined in MATH.ff, stores
error information for math routines. It is used by the
matherr routine.
FILE The FILE structure, defined in STDIO.ff, is the
structure used in all stream input and output opera­
tions. The fields of the FILE structure store informa­
tion about the current state of the stream.
find_t The find t structure, defined in DOS.H, stores file­
attribute information returned by the _dos_findfirst
and dos findnext routines.
fpos_t The fgetpos and fsetpos functions use the fpos_t ob­
ject type, defined in STDIO.ff, to record all the infor­
mation necessary to uniquely specify every position
within the file.
jmp_buf The jmp_buf type, defined in SETJMP.H, is an
array type rather than a structure type. A buffer of
this type is used by the setjmp and longjmp
routines to save and restore the program
envfronment.
lconv The lconv type is a structure containing formatting
rules for numeric values in different countries. It is
defined in LOCALE.ff.
70 Microsoft C Run-Time Library Reference

onexit_t The onexit routine is declared as an onexit_t pointer


type, which is defined in STDLIB.ff.
ptrdift'_t The ptrdift'_t type is used for the signed integral re­
sult of the subtraction of two pointers.
REGS The REGS union, defined in DOS.ff, stores byte and
word register values to be passed to and returned
from calls to the DOS interface functions.
sig_atomic_t The sig_atomic_t type, defined in SIGNAL.ff, is the
integral type of an object that can be modified as an
atomic entity, even in the presence of asynchronous
interrupts. It is used in conjunction with the signal
routine.
size_t The size_t type, defined in STDDEF.ff and several
other include files, is the unsigned integral result of
the sizeof operator.
SREGS The SREGS structure, defined in DOS.ff, stores the
values of the ES, CS, SS, and DS registers. This
structure is used by the DOS interface functions that
require segment register values (int86x, intdosx,
and segread).
stat The stat structure, defined in SYS\STAT.ff, con­
tains file-status information returned by the stat and
fstat routines.
time_t The time_t type, defined in TIME.ff, represents
time values in the mktime and time routines.
timeb The timeb structure, defined in SYS\TIMEB.ff, is
used by the ftime routine to store the current system
time.
tm The tm structure, defined in TIME.ff, is used by the
asctime, gmtime, and localtime functions to store
and retrieve time information.
utimbuf The utimbuf structure, defined in SYS\UTIME.ff,
stores file access and modification times used by the
utime function to change file-modification dates.
va_list The va_list array type, defined in STDARG.ff, is
used to hold information needed by the va_arg
macro and the va end routine. The called function
declares a variable of type va_list, which may be
passed as an argument to another function.
PART 2

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

About the Run- Time Reference


The following pages describe, in alphabetical order, the more than 400 func­
tions in the Microsoft run-time library. In some cases, related routines are
clustered in the same description. For example, the based, near, and far versions
of _heapwalk are in the same discussion, as are the regular and long double
versions of the math functions, such as acos and atan. Differences are noted
where appropriate. Refer to Chapter 2, "Run-Time Routines by Category," or
to the index to locate any function that does not appear in the expected position
within the alphabeHcal reference.
The discussion of each function (or group of functions) is divided into the follow­
ing sections:
• Description. Summarizes the routine's effect, names the include file(s) contain-
ing its declaration, illustrates the syntax, and briefly describes the arguments.
• Remarks. Gives a more detailed description of the routine and how it is used.
• Return Value. Describes the value returned by the routine.
• Compatibility. Tells whether the routine is compatible with ANSI C, MS-DOS,
OS/2, UNIX , and XENIX.
• See Also. Names related routines.
• Example. Gives a complete program showing the use of the routine.
abort 76

Description Aborts the current process and returns an error code.

#include <process.h> Required only for function declarations; use either


#include <Stdlib.h> PROCESS.H or STDLIB.H

void abort( void );

Remarks The abort function prints the message


a b n o rma l p r o gr a m t e rm i n a t i o n

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.

Compatibll/ty • ANSI • DOS • OS/2 • UNIX • XENIX

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 ;

i f( ( s t r e a m = fo p e n ( " NOSUCH F . I LE " , " r " ) ) = NU L L )


{
p e r ro r ( " C o u l d n ' t o p e n f i l e " ) ;
abort ( ) ;

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

Description Calculates the absolute value.

#include <Stdlib.h> Required only for function declarations; use either STDLIB.H
#include <math.h> or MATH.H

int abs( int n );

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.

Campallbility • ANSI • DOS • OS/2 • U N IX • XENIX

See Also cabs, fabs, labs

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 .
*/

#i n c l ude < s t d i o . h>


#i n c l u d e <ma t h . h >
#i n c l ude < s t d l i b . h>

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

The a bsol ute v a l ue of -4 i s 4


The absol ute v a l ue of - 4 1 567 i s 4 1 567
The a bsol ute va l ue o f - 3 . 1 4 1 593 i s 3 . 1 4 1 59 3
access 80

Description Detennines file-access pennission.

#include <io.h> Required only for function declarations


#include <errno.h> Required for definition of errno constants

int access( char *pathname, int mode );

pathname File or directory path name


mode Pennission setting

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

Campatlblllly D ANSI • DOS • OS/2 • UNIX • XENIX

See Also chmod, fstat, open, stat

I * A C C E S S . C : T h i s e x a m p l e u s e s a c c e s s t o c h e c k t h e f i l e n a med " d a t a "


* t o s e e i f i t e x i s t s a n d i f w r i t i n g i s a l l ow e d .
*/

#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

Description Calculate the arccosine.

#include <math.h>
#include <errno.h> Required for definition of ermo constant

double acos( double x );


long double acosl( long double x );

x Value whose arccosine is to be calculated

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

• ANSI • DOS • OS/2 • UNIX • XENIX

acosl

0 ANSI • DOS • OS/2 0 UNIX 0 XEN IX

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 ;

p r i n t f C " E n t e r a r e a l n umbe r b e t w e e n - 1 a n d 1 : • >;


s c a n f ( " % l f " , &x > :
y = asi n( x > :
pr i ntf( "Arcs i ne of %f = %f\ n " , x , y > :
y = a c os C x > :
p r i nt f ( " A rc c os i n e o f % f = % f\ n " , 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

Description Allocates memory on the stack.

#include <malloc.h> Required only for function declarations

void *alloca( size_t size );

size Bytes to be allocated from stack

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 ) ;

voi d func < reg i s t e r i n t


(
a l l oca ( i ) ;

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

Compatibility D ANSI • DOS • OS/2 • U N IX D XENIX

S11 A/Ba calloc functions, malloc functions, realloc functions

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 :

p r i n t f ( " By t e s a va i l a b l e on s t a c k : % u \ n " , s t a c k a v a i l ( ) > :

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

Description Draw elliptical arcs.

#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 ) ;

xl , yl Upper-left comer of bounding rectangle


x2, y2 Lower-right comer of bounding rectangle
x3, y3 Second point of start vector (center of bounding rectangle is
first point)
x4, y4 Second point of end vector (center of bounding rectangle is
first point)
pwxyl Upper-left comer of bounding rectangle
pwxy2 Lower-right comer of bounding rectangle
pwxy3 Second point of start vector (center of bounding rectangle is
first point)
pwxy4 Second point of end vector (center of bounding rectangle i.s
first point)

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.

Campatlbllity D ANSI B DOS D OS/2 D UNIX D XENIX

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 . * /

#i n c l ude < g r a p h . h >


#i n c l u d e < s t d l i b . h >
#i n c l u d e < c o n i o . h >

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 );

I * Get e n d po i n t s o f s econd a rc a n d encl o s e t h e f i g u re , t h en f i l l i t . * /


_g et a rc i n f o ( &xys t a rt , &xyend , &xy f i l l ) ;
_mo v e t o < xys t a rt . x c o o rd , xysta rt . y c o o rd ) ;
_l i n e t o ( xyend . xc o o r d , xyend . y c o o rd ) ;
_fl o o d f i l l ( xyf i l l . xc o o r d , xyfi l l . ycoord , _g et c o l o r ( ) ) ;

getch ( ) ;
_s e t v i d e omod e ( _D E FAU LTMOD E ) ;
asctime 88

D11t:rlpllan Converts a tm time structure to a character string.

#include <time.h>

char *asctime( const struct tm *timeptr ) ;

timeptr Time/date structure

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)

int tm_mday Day of the month (0-3 1 )


int tm_mon Months since January (0-1 1)

int tmJear Years since 1900


int tm_wday Days since Sunday (0-6)
int tmJday Days since January 1 (0-365)
int tm_isdst Daylight-saving-time flag

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

Campaliblllly • ANSI • DOS • OS/2 • UNIX • XEN IX

See Also ctime, ftime, gmtime, localtime, time, tzset

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 * /

n ewt i me = l oc a l t i me C & a c l o c k > : I * C o n v e r t t i me t o s t ruct tm fo rm * /

/ * 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

Description Calculate the arcsine.

#include <math.h>
#include <errno.h>

double asin( double x );


long doubie asinl( long double x );

x Value whose arcsine is to be calculated

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

• ANSI • DOS • OS/2 • UNIX • XENIX

asinl

0 ANSI • DOS • OS/2 0 UNIX 0 XEN IX

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

E n t e r a rea 1 number between - 1 and 1 : . 32696


A r c s i n e o f 0 . 3 2 6 9 60 = 0 . 3 3 3085
A r c c o s i n e o f 0 . 3 2 6 9 60 = 1 . 23 7 7 1 1
assert 92

Dacr/pllon Prints an error message and aborts the program.

#include <assert.h>
#include <Stdio.h>

void assert( int expression );

expression C expression specifying assertion being tested

Remadrs The assert routine prints a diagnostic message and calls the abort routine if expression is
false (0). The diagnostic message has the form

A s s e rt i o n fa i l ed : expression , fi l e filename , l i n e linenumber

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.

The assert routine is implemented as a macro.

Return Value None.

Compallb/llly • ANSI • DOS • OS/2 • UNIX • XENIX

See Also abort, raise, signal

I * ASS E RT . C : I n t h i s p ro g r a m , t h e a n a l y z e_s t r i ng fun c t i on u s e s t h e


* a s s e rt f u n ct i on t o t e s t s ev e r a l con d i t i on s rel a t ed t o s t r i ng a n d
* l en gt h . I f a ny o f t h e c o nd i t i on s fa i l s , t h e p r o g r a m p r i n t s a
* mes s a g e i nd i c a t i n g w h a t c a u s ed t h e fa i l u r e .
*I

#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 [ ] = .

p r i n t f ( " An a l y z i n g s t r i ng ' % s ' \ n " , t e s t l ) ;


a n a l y ze_s t r i n g ( t e s t l ) ;
p r i n t f C " An a l y z i n g s t r i n g ' %s ' \ n " , t e s t 2 ) ;
a n a l y ze_s t r i n g ( t e s t 2 ) ;
p r i n t f C " An a l y z i n g s t r i n g ' %s ' \ n " , t e s t 3 ) ;
a n a l y z e_st r i n g ( 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>

double atan( double x ) ;


double atan2( double y, double x ) ;
long double atanl( long double x ) ;
long double atan21( long double y, long double x );

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.

Compatibility atan, atan2

• ANSI • DOS • OS/2 • UNIX • XENIX

atanl, atan21

0 ANSI • DOS • OS/2 0 UNIX 0 XENIX

SBB A/so acos functions, asin functions, cos functions, matherr, sin functions, tan functions

I * ATAN . C : 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 r c t a ngent of 1 and -1. */

#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:

p r i n t f { " E n t e r a rea l n umbe r : " ) ;


s c a n f { " % l f " , &xl > :
y = ata n { xl l :
p r i n t f ( " A r c t a n gent of %f : % f \ n " , x l , y l :
p r i n t f ( " En t e r a s ec o n d rea l n umbe r : " l :
s c a n f { " % l f " , &x2 l :
y = a t a n 2 ( x l , x2 ) ;
p r i n t f ( " A r c t a n g ent o f % f I %f : % f \ n " , x l , x 2 , 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

Description Processes the specified function at exit.

#include <Stdlib.h> Required only for function declarations

int atexit( void ( *June )( void ) );

June Function to be called

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).

Compatibility • ANSI • DOS • OS/2 0 UNIX 0 XENIX

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.

See Also abort, exit, _exit, onexit

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 fn l ( v o i d } , fn2 ( v o i d } , fn3 C v o i d } , fn4 C v o i d } ;

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).

#include <math.h> atof, _atold


#include <Stdlib.h> atof, _atold, atoi, atol

double atof( const char *string );


long double _atold( const char *string );
int atoi( const char *string );
long atol( const char *string );

string String to be converted

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.

Campatlblllty atof, atoi, atol

• ANSI • DOS • OS/2 • UNIX • XEN IX

_atold

D ANSI • DOS • OS/2 D U N IX D XENIX

SBB A/Ba ecvt, fcvt, gcvt

I * ATO F . C : T h i s p r o g r a m s h ows h ow n umb e r s s t o red a s s t r i n g s c a n be


* c o n v e rted t o n ume r i c v a l u e s u s i n g the a t o f , a t o i , a nd atol func t i o n s .
*I

#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 = " 7 . 89 1 2 6 5 4 7 7 3 d 2 1 0 " ; / * T e s t of a tof * /


x "' a t o f C s ) ;
p r i ntf ( " a to f t e s t : ASC I I s t r i n g : % s \ t f l oa 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 , );

s = " 98854 d o l l a r s " ; / * T e s t of a to l * /


1 = a tol C s > ;
p r i n t f ( • a t o l t e s t : ASC I I s t r i n g : % s \ t \ t l ong : %l d\n " , S, 1 ) ;
ataf, atai, atal, _atald 100

Output

atof t es t : ASC I I stri ng : - 2309 . 1 2 E- 1 5 fl oat : - 2 . 309 1 2 0 e - 0 1 2


a to f test : ASC I I s t r i n g : 7 . 89 1 26547 7 3 d 2 1 0 fl oa t : 7 . 89 1 2 6 5 e+2 1 0
atoi t es t : A SC I I stri ng : - 9885 p i g s i n teg e r : - 9885
a tol test : A SC I I s t r i n g : 98854 d o l l a r s 1 ong : 98854
101 bdos

Description Invokes the DOS system call.

#include <dos.h>

int bdos( int dosfunc, unsigned int dosdx, unsigned int dosal );

dosfunc Function number


dosdx DX register value
dosal AL register value

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.

Compallblllty D ANSI • DOS D OS/2 D UNIX D XEN IX •

See Also intdos, intdosx

I * BDOS . C : T h i s exampl e c a l l s DOS fun c t i on 0x9 ( d i s p l ay s t r i n g )


* t o d i s p l a y a $ - t e rmi n a ted s t r i n g .
*I

/Ii n c l ude < d o s . h >


bdos 102

/ * Func t i on 0x09 a s s umes t h a t D S w i l l c o n t a i n s egment of t h e s t r i n g ,


* T h i s w i l l be t r u e f o r a l l memo ry model s i f t h e s t r i n g i s d e c l a red nea r .
*I
c h a r _n ea r s t r [ J
= " H e l l o worl d ! \ r \ n $ " ;

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

DISCl'lpllon Begins thread in OS/2 process.

#include <process.h> Multithread version of PROCESS.ff


#include <Stddef.h> Declaration of threadid variable

int _far _beginthread( void( _far *start_address ) ( void _far * ),


void _far *stack_bottom, unsigned stack_size, void _far *arglist );

start address Starting address


stack bottom Address of the thread stack
stack size Stack size for thread
arglist Argument list for thread

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.

The stack_size argument must be even and nonzero.


If you are writing multithread programs that make C run-time calls from child threads, be
sure to allocate a sufficiently large stack. For example, the C function printf requires
more than 500 bytes of stack space. To be safe, allocate at least 2 ,048 bytes for a thread's
stack. (If your child thread makes no run-time calls, stack space is generally not a
problem.)
As a general rule, you should have 2K of stack space free when calling any API (Applica­
tions Program Interface) routine (e.g., OS/2 system calls).
The arglist is a parameter, the size of a far pointer, to be passed to the newly created
thread. Typically it is the address of a data item, such as a character string, to be passed to
the new thread. The arglist may be NULL if not needed, but _beginthread should be pro­
vided with some value to pass to the child thread.
_beginthread 104

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

until other threads have tenninated before exiting the program.

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

EAGAIN Too many threads

EINVAL Invalid argument, "bad stack"

Compallblllty D ANSI D DOS • OS/2 D UNIX D XENIX

S11 Also endthread

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 Bou n c e ( i n t c > : / * P rototypes * /


v o i d C h e c k Key ( v o i d *d ummy } ;
105 _beginthread

I * Get Ra n d om ret u rn s a r a n d om i nt e g e r between mi n a n d m a x . * /


#d ef i n e Get R a n d o m ( mi n , ma x ) ( ( ra nd ( ) % C i n t ) ( ( ( ma x ) + 1 ) - ( mi n ) ) ) + ( mi n ) )

#de f i n e STAC K_S I Z E 4096

BOO L repeat = T RU E : / * Gl oba l repe a t fl a g a n d v i deo v a r i a b l e * /


V I OM O D E I N FO v m i = { s i zeof ( V I OMOD E I N FO ) l :

v o i d ma i n ( )
{
PCHAR s ta c k :
CHAR ch = 'A' ;

I * Get d i s p l a y s c reen ' s text row a nd c o l umn i n fo rma t i on . * /


V i oGetMod e C &vmi , 0 > :

I * La u n c h C h e c kKey t h rea d t o c h e c k for t e rmi n a t i n g key s t roke . * /


_beg i n t h rea d ( C h e c k Key , N U L L , STAC K_S I Z E , N U L L > :

I * Loop u nt i l C h e c k Key t e rmi n a t e s p rog ram . * /


w h.i 1 e ( repe a t >
{
I * On f i r s t l oops , l a u n c h c h a r a c t e r t h re a d s . * /
_beg i n t h rea d ( B o u nc e , N U L L , STAC K_S I Z E , ( v o i d * ) c h++ > :

I * Wa i t one s ec o n d betwe en l oops . * /


D o s S l eep C 1000 L > :

I * C h e c k Key - T h read t o wa i t f o r a key s t ro k e , t h e n c l ea r repeat fl a g . * /


v o i d C h ec k Key ( v o i d *d ummy )
{
getch C > :
repea t = 0 ; I * _en d t h r e a d i mp l i ed * /

/ * 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

Description Compute the Bessel function.

#include <math.h>

double jO( double x );


double jl( double x );
double jn( int n, double x );
double yO( double x );
double yl( double x );
double yn( int n, double x );
long double JOI( long double x );
long double Jnl( int n, long double x );
long double Jll( long double x );
long double JOI( long double x );
long double Jll( long double x. );
long double Jnl( int n, long double x );

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

Return Value These functions return the result of a Bessel function of x.

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.

Campatlblllty jO, j l, jn, yO, yl, yn

0 ANSI • DOS • OS/2 • UNIX • XENIX

JOI, j ll, jnl, _yOI, _yll, _ynl

0 ANSI • DOS • OS/2 0 UNIX 0 XENIX

See Also matherr

I * B E SS E L . C : Th i s program i l l ustrates Bessel functi ons , i ncl udi ng :


* j0 jl jn y0 yl yn
*I

#i n c l ude <ma t h . h >


#i n c l ude < s t d i o . h>

v o i d ma i n ( )
(
d o u b l e x = 2 . 387 ;
i nt n = 3, c;

p r i n t f C " B e s s e l f u n c t i o n s for x = %f : \ n " , x > :


pri ntf( • K i n d \ t \ t O r d e r \ t \ Fu n c t i on \ t Re s u l t \ n \ n " > :
pri ntfC • F i r s t \ t \ t0 \ tj 0 C x ) \ t \ t % f \ n " , j 0 ( x ) > :
pri ntfC • F i rs t \ t \ t l \ t j l C x ) \ t \ t % f \ n " , j l ( x ) > :
for ( c = 2 ; c < 5 ; c++ >
pri ntf( • F i r s t \ t \ t% d \ t j n ( n , x ) \ t % f \ n " , c , j n ( c , x ) > :

pri ntf( Second \ t 0 \ ty0 ( x ) \ t \ t % f \ n " , y0 C x ) ) ;


pri ntf( Second \ t l \ ty l ( x ) \ t \ t % f \ n " , y l ( x ) > :


for ( c = 2 ; c < 5 ; c++ )


pri ntf ( S e c o n d \ t%d \ tyn ( n , x ) \ t % f \ n " , c , yn ( c ,
• x ) ) ;
109 Bessel Functions

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

Fi rst 0 j0( x ) 0 . 009288


Fi rst 1 j1( x ) 0 . 522941
Fi rst 2 jn( n, x 0 . 428870
Fi rst 3 jn( n, x 0 . 195734
Fi rst 4 jn( n, x 0 . 063131
Second 0 y0 ( x ) 0 . 5 1 1 681
Second 1 yl ( x ) 0 . 094374
Second 2 yn ( n, x -0 . 4 3 2 608
Second 3 yn ( n, x -0 . 819314
Second 4 yn ( n, x - 1 . 626833
_bfreeseg 1 10

Description Frees a specified based heap.

#include <malloc.h> Required only for function declarations

int _bfreeseg( _segment seg ) ;

seg Segment selected

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.

Compatibility D ANSI • DOS • OS/2 D UNIX D XENIX

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 ;

pri ntf( " Enter a stri ng : " ) ;


g e t s ( tmp s t r ) ;

/ * Req u e s t a b a s ed h e a p . U s e ba s ed s o t h a t memory won ' t be t a ken f rom


* nea r hea p .
*/
111 _blreeseg

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

p o u t < o u t s t r + l e n ; p i n - - , p o u t++ >


*pout - *pi n ;
*pout - ' \ 0 ' ;

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

DIJllJl'lpt/on Allocates a based heap.

#include <malloc.h> Required only for function declarations

_segment _bheapseg( size_t size );

size Segment size to allocate

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.

Compat/bll/ly 0 ANSI • DOS • OS/2 0 UNIX 0 XENIX

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

#i n c l ude <stdi o . h>


#i n c l u d e <ma l l oc . h>
#i n c l ude <stdl i b . h>
#i n c l ude < s t r i n g . h>
1 13 _bheapseg

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 ) ;

I * Req u e s t a ba s ed h ea p . U s e ba s ed s o t h a t memo ry won ' t be ta ken f rom


* n e a r h ea p .
*I
i f ( ( s eg = _b h e a p s e g ( 1 000 ) ) _N U L L S E G )
==

exi t ( l ) ;

I * Al l o c a t e ba s ed memo ry for two s t r i n g s . * /


l en = s t r l en ( tmp s t r ) ;
i f( ( ( i nstr = _bma l l oc C s eg , l en + l ) ) _N U L LO F F ) I I
==

( ( outstr = _bma l l o c ( s eg , l e n + l ) ) _NU L LO F F ) )


==

exi t ( l ) ;

I * Copy a l owerca s ed s t r i n g t o dynami c memo ry . The 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
_fs t r l w r < _f s t rc py ( ( c h a r _fa r * ) i n s t r , ( c h a r _fa r * ) tmp s t r > ) ;

/ * 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

Description Calls BIOS disk services using system call INT Ox 1 3.

#include <bios.h>

unsigned _bios_disk( unsigned service, struct diskinfo_t *diskinfo );

service Disk function desired

diskinfo Disk parameters

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.

The diskinfo structure provides the following parameters:

Element Description
unsigned drive Drive number

unsigned head Head number


unsigned track Track number

unsigned sector Starting sector number

unsigned nsectors Number of sectors to read, write, or compare

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
_ .

the return value, as listed below:

Bits Meaning

OxO l ** Invalid request or a bad command

Ox02** Address mark not found


Ox04** Sector not found
Ox05** Reset failed
Ox07** Drive parameter activity failed
Ox09** Direct Memory Access (DMA) overrun
OxOA** Bad sector flag detected
Ox I O** Data read (ECC) error
Ox l l ** Corrected data read (ECC) error
Ox20** Controller failure
Ox40** Seek error

Ox80** Disk timed out or failed to respond


OxAA** Drive not ready

OxBB** Undefined error

OxCC** Write fault on drive


OxEO** Status error

_ 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
_

operation, such as a read. If this service is specified, the


diskinfo argument is ignored.
_ DISK STATUS
_ Obtains the status of the last disk operation. If this service is
specified, the diskinfo argument is ignored.
117 _bias_ disk

_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.

Campat/blllty D ANSI • DOS D OS/2 D U N IX D XENIX

&amp• ��
����---

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>

unsigned _bios_equiplist( void );

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

0 Any disk drive installed if true


1 True ( 1) if math coprocessor installed
2 -3 System RAM in 16K blocks ( 16-64K)

4 -5 Initial video mode

6 -7 Number of floppy-disk drives installed (00 = 1 , 0 1 = 2, etc.)

8 False (0) if and only if a Direct Memory Access (OMA) chip


is installed

9 -1 1 Number of RS232 serial ports installed

12 True ( 1 ) if and only if a game adapter is installed

13 True ( 1 ) if and only if an internal modem is installed

14-15 Number of printers installed

Compal/bl/lty D ANSI • DOS D OS/2 D U N IX D XENIX

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

Description Calls BIOS keyboard services, using INT Ox 1 6.


#include <bios.h>

unsigned _bios_keybrd( unsigned service );

service Keyboard function desired

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

_KEYBRD_Slm'TSTATUS, Returns the current SHIFl'-key status. Only


_NKEYBRD_Slm'TSTATUS the low-order byte of the return value is af­

constant is used to get a full 1 6-bit status


fected. The NKEYBRD SHIFTSTATUS

value. Any combination of the following


bits may be set:

Bit Meaning if True


OOH Rightmost SHIFI' key pressed
OlH Leftmost SHIFI' key pressed
02H Either CTRL key pressed
3H Either ALT key pressed
04H SCROLL LOCK on
05H NUM LOCK on
06H CAPS LOCK on

07H In insert mode (INS )


OSH Left CTRL key pressed
09H Left ALT key pressed
OAH Right CTRL key pressed
OBH Right ALT key pressed
OCH SCROLL LOCK key pressed

OOH NUM LOCK key pressed

OEH CAPS LOCK key pressed

OFH SYS REQ key pressed

Return Value With the ""READ and SHIFrSTATUS arguments, the _bios_keybrd function returns the
•••

contents of the AX register after the BIOS call.


With the ...READY argument, _bios_keybrd returns 0 if there is no key. If there is a key,
_bios_keybrd returns the key waiting to be read (i.e. the same value as _KEYBRD_READ).
With the ...READ and the ".READY arguments, the _bios_keybrd function returns -1 if
CTRL+BREAK has been pressed and is the next keystroke to be read.
123 _bios_ksybrd

Compatibility 0 ANSI • DOS D OS/2 D U N IX 0 XENIX

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

U s e t h e r i g h t S H I FT key to stop thi s mes s a g e


U s e t h e r i g h t SH I FT key to stop thi s mes s a g e
U s e t h e r i g h t SH I FT key to stop thi s mes s a g e
U s e t h e r i g h t SH I FT key to stop thi s me s s a g e
Ri g h t SH I FT key p r e s s ed
_bios_memsize 124

Description Calls the BIOS memory-size service, using system call INT Ox1 2.

#include <bios.h>

unsigned _bios_memsize( void );

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.

Campatlblllly D ANSI • DOS D OS/2 D UNIX D XENIX

I* BMEM S I Z E . C : T h i s p r o g ram d i s p l ays t h e amount of memo ry i n s t a l l ed . * /

#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

DBScr/ptian Calls BIOS printer services using system call INT Ox 1 7.

#include <bios.h>

unsigned _bios_printer( unsigned service, unsigned printer, unsigned data );

service Printer function desired


printer · Target printer port
data Output data

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:

Bit Meaning if True


0 Printer tim(:Cl out
Not used
2 Not used
3 UO error
4 Printer selected
5 Out of paper
6 Acknowledge
7 Printer not busy
_bios_printer 126

R11tum Value The _bios_printer function returns the value in the AX register after the BIOS interrupt.

Campal/blllty 0 ANSI • DOS 0 OS/2 0 UNIX 0 XEN IX

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 ;

p r i n t f C " P l a c e p r i n t e r off l i n e a n d p r e s s a ny key \ n " > :


getc h C > :

s t a t u s = _b i o s_p r i n t e r ( _P R I NT E R_STAT U S , LPTl , 0 ) ;


p r i n t f ( " St a t u s w i t h p r i n t e r off l i n e : 0x% . 4x \ n \ n " , s t a t u s > :
p r i n t f ( " P ut t h e p r i n t e r on l i n e a n d t h en \ n " > :
p r i n t f C " P re s s a ny k ey t o i n i t i a l i z e p r i n t e r \ n " > :
getc h ( ) ;

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>

unsigned _bios_serialcom( unsigned service, unsigned serial_port, unsigned data );

service Communications service


serial_port Serial port to use
data Port configuration bits

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

The data argument is ignored if service is set to _COM_RECEIVE or _COM_STATUS.


The data argument for _COM_INIT is created by combining (with the OR operator) one or
more of the following constants:

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

_COM_EVENPARITY Even parity


_COM_ODDPARITY Odd parity
_COM_llO l lO baud
_COM_lSO 150 baud
_COM_300 300 baud
_COM_600 600 baud
_COM_1200 l ,200 baud
_COM_2400 2,400 baud
_COM_4800 4,800 baud
_COM_9600 9,600 baud

The default value of data is 1 stop bit, no parity, and 1 10 baud.

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:

Bit Meaning if Set

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:

Bit Meaning if Set


7 Receive-line signal detected
6 Ring indicator
5 Data set ready
4 aear to send
3 Change in receive-line signal detected
2 Trailing-edge ring indicator
1 Change in data-set-ready status
0 Change in clear-to-send status

Note that this function works only with IBM personal computers and true compatibles.

Campatlblllty D ANSI • DOS D OS/2 D UNIX D XENIX

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 ;

c oml_s t a t u s = _b i o s_s e r i a l c om ( _C OM_STAT U S , 0 , 0 ) ;


p r i n t f < " COMl s t a t u s : 0x% . 4 x \ n " , c oml_s t a t u s l ;

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>

unsigned _bios_timeofday( unsigned service, long *timeval );

service Time function desired

timeval Oock count

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

Compallblllty 0 ANSI • DOS 0 OS/2 0 U N IX D XEN IX

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

#i n c l ude < s � d i o . h >


#i n c l u d e < b o s . h >
I
131 _bios_ti111eolday

v o i d ma i n { )
(
l ong i , b e g i n_t i c k , end _t i c k ;

_b i o s_t i meofd a y { _ TIM G TCLOCK


E_ E , & b e g i n_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 ) ;

_b i os_t i meofd a y { _ TIM G TCLOCK


E_ E , &end_t i c k ) ;

p r i n t f { " En d i n g t i c k count : %l u \ n " , end_t i c k > :


p r i n t f { " El a p s e d t i c k s : %l u \ n " , end_t i c k - begi 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

Description Perfonns binary search of a sorted array.

#include <Stdlib.h> Required for ANSI compatibility

#include <Search.h> Required only for function declarations

int ( *compare )( const void *eleml , const void *elem2 ) ) ;


void *bsearch( const void *key, const void *base, size t num, size t width,
-

key Object to search for


balse Pointer to base of search data

num Number of elements

width Width of elements

compare Function that compares two elements: eleml and elem2

elem} Pointer to the key for the search

elem2 Pointer to the array element to be compared with the key

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

<0 eleml less than elem2


=0 eleml identical to elem2
>0 eleml greater than elem2

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

Campallblllty • ANSI • DOS • OS/2 • UNIX • XENIX

See Also Hind, lsearch, qsort

/ * B S EARCH . C : T h i s p r o g r a m rea d s t h e c omma n d - l i n e a r g ument s , s o rt i n g t h em


* w i t h q s o rt , a n d t h en u s e s b s e a r c h t o f i n d t h e word " c a t . "
*I

#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 > ·

i n t c ompa re ( c h a r **a rg l , c h a r **a rg2 > : / * Dec l a re a f u n c t i on f o r c ompa re * /

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 > :

f o r e i = 0 ; i < a r g c ; ++i } / * O u t p u t s o rted l i s t * /


p r i n t f ( " %s • , a rg v [ i ] > :

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 " > :

i n t c ompa re ( c h a r **a rg l , c h a r **a rg2


(
I * C omp a re a l l o f b o t h s t r i n g s : * /
r e t u r n s t rcmp i ( * a r g l , * a rg2 } ;

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

Dncrlpllan Calculate absolute value of a complex number.

#include <math.h>

double cabs( struct complex z );


long double cabsl( struct _complexl z );

. 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:

sqrt( z.x*z.x + z.y*z.y )

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

D ANSI • DOS • OS/2 • UNIX • XENIX

cabsl

D ANSI • DOS • OS/2 D UNIX 0 XENIX

S11 Alsa abs, fabs, labs

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

T h e a bs o l u t e v a l ue o f 3 . 000000 + 4 . 000000i i s 5 . 000000


ca/lac F�nctians
l

136

I
Daer/pt/an I Allocate an array in memory with elements initialized to 0.
I
I

#include <Stdlib.h> For ANSI compatibility (calloc only)


#include <malloc.h> Required only for function declarations

void *calloc( size_t num, size_t size );


void _based( void ) *_bcalloc( _segment seg, size_t num, size_t size ) ;
void _far *_fcalloc( size_t num, size_t size );
void _near *_ncalloc( size_t num, size_t size );

num Number of elements


size Length in bytes of each element
seg Segment selector

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

• ANSI • DOS • OS/2 • UNIX • XENIX

_bcalloc, _fcalloc, _ncalloc

D ANSI • DOS • OS/2 D UNIX D XENIX

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

Oat:r/pt/an Calculate the ceiling of a value.

#include <math.h>

double ceil( double x );


long double ceill( long double x ) ;

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

• ANSI • DOS • OS/2 • UNIX • XENIX

ceill

D ANSI • DOS • OS/2 D UNIX D XENIX

See Also floor, fmod

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 n c l ude <m , t h . h >


#i n c l ude < s f d i o . h >

!
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

The fl oor o f 2 . 8 i s 2 . 000000


The f l oor o f - 2 . 8 i s - 3 . 000000
The c e i l of 2 . 8 i s 3 . 000000
The c e i l of - 2 . 8 i s - 2 . 000000
_cexit _ (L exit
, 140

Description Perform clean-up operations and return without terminating the process.

#include <process.h>

void _cexit( void );


void _c_exit( void );

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

Return Value None.

Compatibility 0 ANSI • DOS • OS/2 0 UNIX 0 XENIX

See Also abort, atexit, exec functions, exit, onexit, spawn functions, system
141 cgets

Description Gets a character string from the console.

#include <conio.h> Required only for function declarations

char *cgets( char *buffer );

buffer Storage location for data

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.

Compatibility D ANSI • DOS • OS/2 D UNIX D XENIX

See Also getch, getche

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 n c l ude < c o n i o . h >


#i n c l ude < s t d i o . h >
cgets 142

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 ;

I n p u t l i n e o text , fol l owed by c a r r i a g e ret u r n :

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

Description Chains an interrupt from one handler to another.

#include <dos.h>

void _chain_intr( void( _interrupt _far *target )( ));

target Target interrupt routine

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.

v o i d _i n t e r rupt n ew_i nt ( u n s i gned _es , u n s i gned _d s ,


un s i gned _d i , u n s i gned _s i , . . . l

++_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.

voi d _i n t e r rupt n ew_i nt ( u n s i gned _es , u n s i gned _d s ,


u n s i gned _d i , u n s i gned _s i , . . >
.

++_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

See Also _dos_getvect, _dos_keep, _dos_setvect


145 chdir

Description Changes the current working directory.

#include <direct.h> Required only for function declarations


#include <errno.h> Required for errno constants

int chdir( char *dirname ) ;

dirname Path name of new working directory

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.

Compatibility D ANSI • DOS • OS/2 • UNIX • XENIX


chdir 146

See Alsa _dos_setdrive, mkdir, rmdir, system

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

* the c u r rl e n t d i rec t o ry . U n d e r p rotected mod e , i t i s o n l y t h e d e fa u l t


* g i ven d i1 r e c t o ry e x i s t s . U n d e r rea l mod e t h a t d i r e c t o ry a l s o becomes

* d i recto rly f o r t h e c u r rent p r o c e s s .


*I
I
#i n c l ude < � i r ect . h >
#i n c l ude < � td i o . h >
#i n c l ude < � t d l i b . h >

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

The v o l um � l a bel i n d r i v e C i s 052 .


D i r e c t o ry l o f C : \TMP

I
i

DUP c 232 4 - 18-89 1 1 : 18a


T E ST c I 713 4 - 0 7 - 88 2 : 49p
2 Fi l � ( s ) 1 4 1 5 5 7 7 6 byt e s free
I
I
147 _chdrive

Description Changes the current working drive.

#include <direct.h> Required only for function declarations


_

int _chdrive( int drive );

drive Number of new working drive

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.

Compatlblllly D ANS I • DOS • OS/2 D UNIX D XEN IX

See Also chdir, _dos_setdrive, _fullpath, _getcwd, _getdrive, mkdir, rmdir, system

I * GETD R I V