Sie sind auf Seite 1von 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 E . C i l l u s t r a t e s d r i ve f u n c t i on s i n c l ud i n g :
* _g etd r i v e _c h d r i v e _g etd cwd
*I

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


#i n c l u d e <coni o . h>
#i n c l u d e <di rect . h>
#i n c l u d e <stdl i b . h>
_i:hdrivel 148

v o i d ma i n ( ) i
( i
i n t c h , d r i v e , c u rd r i v e ;

s t a t i c c a r p a t h [_MAX_PATH J ;
I
I * S a v e � u r rent d r i v e . * /
c u rd r i v e l = _g etd r i v e ( ) ;

i >;

ti
printfC Av a i l a b l e d r i ves a re : \ n "

I * I f we c a n swi t c h t o t h e d r i v e , i t exi s t s . * /
for( dri e = 1 ; d r i v e < = 2 6 ; d r i ve++ )
i f( ! chdri veC dri ve ) l
pr n t f ( " %c : • , d r i v e + ' A ' - 1 > ;

whi l e( 1 I )

1 �
,
p r i n t ( " \ nTy pe d r i v e l et t e r t o c h e c k o r ESC t o q u i t : • );
c h = �etch ( ) ;
i f ( c � == 27 )
br a k ;
i f ( i a l pha ( c h > l
pu c h ( ch l ;
i f ( - 1 etd cwd ( t o u p pe r ( c h ) - ' A ' + 1 , pa t h , _MAX_PATH ) ! = N U L L
p r l n t f ( " \ n C u r r e n t d i r e c t o ry o n t h a t d r i v e i s % s \ n " , p a t h ) ;

t
* t h e c � rrent d r i v e of t h e c a l l i n g p r o c e s s i s a l ways restored .
/ * Res t o e o r i g i n a l d r i ve . T h i s i s on l y n e c e s s a ry f o r DOS . U n d e r O S / 2

I
_c hd r i v e \ c u r d r i ve ) ;
*I

printf( i \n" ) ;
I

°"""'
Av a i l a b l e d f i v e s a r e :
A: B: C: I
Type d r i v e J e t t e r t o c h e c k o r E S C t o q u i t : q
Ty p e d r i v e 1 e t t e r t o c h e c k or ESC t o q u i t : a
C u r r ent d i r�c t o ry on t h a t d r i v e i s A : \
I
Type d r i v e � e t t e r t o c h e c k o r ESC to q u i t : c
C u r rent d i r r c t o ry on t h a t d r i v e i s C : \ L I B R E F

Ty p e d r i v e � etter to chec k or ESC to qui t :


149 chmod

Daer/pl/on Changes the file-pennission settings.

#include <Sys\types.h>
#include <Sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations

int chmod( char *filename, int pmode );

filename Path name of existing file

pmode Pennission setting for file

Rematks The chmod function changes the pennission setting of the file specified by filename. The
pennission setting controls read and write access to the file. The constant expression
pmode contains one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SYS\STAT.H. Any other values for pmode are ignored. When both constants are given,
they are joined with the bitwise-OR operator ( I ) . The meaning of the pmode argument is
as follows:

Value Meaning
S_IWRITE Writing pennitted

S_IREAD Reading pennitted

S_IREAD I S_IWRITE Reading and writing pennitted

If write pennission is not given, the file is read-only. Under DOS and OS/2, all files are
readable; it is not possible to give write-only pennission. Thus the modes S_IWRITE and
S_IREAD I S_IWRITE are equivalent

Rllllrl n Value The chmod function returns the value 0 if the pennission setting is successfully changed.
A return value of -1 indicates an error; in this case, ermo is set to ENOENT, indicating
that the specified file could not be found.
ch mod 150

Compatib /11� D ANSI • DOS • OS/2 • UNIX • XENIX

See Also access, creat, fstat, open, stat

I*I** CHMOD.
read-on�C�, yThis. I t progra then attem usmeptss chtomodmodito fychangethe filthee . mode of a file to
#i#i#i nnnclude
clude
i
<
< �ys\tys\sytpes.at . h>h>
#i#i nnclude
clude
clude <"o.
<�t
<Ftdli d h >
io. b h. >h>
voi dI*maiMaken ( �j·) file read-onl y : */
I

ielsef ( perrchm d(r( "F" CHMOD.i le notC ", found\n"


i

S_IREAD ); )
sIy*spritChan�e
emnc tf(l • echoback" Mode/*tochange
Enread ofd/dwfileritote:read-o
*/*/ nCHMDD.
l y \n" C);"
) � -1

if(elseperrorC
chmpdC ""FCHMOD.i le notC ", found\n" S_IWRITE )
» >:
:

pri n�fC "Mode changed to read/wri te\n"


l == -1
l ;
!
>:
'

ModeAccess iden'' dedto read-onl y


chang
Output
i

Mode chang d to read/wri te


!
151 chsize

DllBt:ription Changes the file size.

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

#include <errno.h>

int chsize( int handle, long size );

handle Handle referring to open file

size New length of file in bytes

Rematks The chsize function extends or truncates the file associated with handle to the length
specified by size. The file must be open in a mode that pennits writing. Null characters
('\0') are appended if the file is extended. If the file is truncated, all data from the end of
the shortened file to the original length of the file is lost.

In DOS, the directory update is done when a file is closed. Consequently, while a program
is running, requests to detennine the amount of free disk space may receive inaccurate
results.

Retum Value The chsize function returns the value 0 if the file size is successfully changed. A return
value of -1 indicates an error, and ermo is set to one of the following values:

Value Meaning
EACCES Specified file is locked against access (OS/2 and DOS
versions 3.0 and later only).

EBADF Specified file is read-only or an invalid file handle.

ENOSPC No space is left on device.

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

S11 A/so close, creat, open

fi l e beforeThisandprogra
I * CHS I ZE . C :
*
*I
aftermmodiusesfyfii ngl eli tengthwi thtochsirezpore. t the si ze of a
chsize

#i#i#i/ i nnnnclude <i � . h >


152

clude
clude
clude
I
<f�ntl.
<s
<s �
� s\
s\sta t y h >
pes.
t . h h
> >
#ivoindcludemai n<s�di() o . h>
I

unsiintOpengfh,ned�esulli nfilet nbt :ytes BUFS I Z :


!
( i

if( pri( fnht ( open("File "dlength ata", Obefore:


_RDWR %lO_dCRE\ n ",AT,filelength(
S_IREAD Sf_h IW) RI);TE ))
=

I

1 I I
I* */

if(elsepric�silntf(z eC " Sfh,i ze successfull y changed\n" );


! = -1
( :

priclose(prntl1 nC fhtf("File);"Prolength
blem inafchangi
ter: n%lgdthe\n ", sifilelengthC
ze\n " fh ) );
329678 > == 0 >

I
> :

SiFileFileze length !b efore:y changed


successfull I
Output

length �fter: I
0

329678
153 _clear87

Description Gets and clears the floating-point status word.

#include <float.h>

unsigned int _clear87( void );

Remarks The _clear87 function gets and clears the floating-point status word. The floating-point sta­
tus word is a combination of the 8087 /80287 status word and other conditions detected by
the 8087/80287 exception handler, such as floating-point stack overflow and underflow.

Retum Value The bits in the value returned indicate the floating-point status. See the FLOAT.ff include
file for a complete definition of the bits returned by _clear87.
Many of the math library functions modify the 8087/80287 status word, with unpredict­

floating-point operations are perfurmed between known states of the floating-point status
able results. Return values from clear87 and status87 become more reliable as fewer

word.

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

See Also _control87, _status87

I*
thenCLEAR8us7.eCs :_clear
This 8progra7 to mreporcreatteson thesvari eousprofloatiblems.ng-point probl ems,
#i#ivoinndclude
clude <stdi<floaot .. hh>>
*
*/

( doublfloatmain()ex,a = le-40, b;
pri Store
ntf( " Si tatus:
y;

%. 4 x - cle a r\n", _cle


nto is%. 4i xnexa- ci tnexandact,underflows: a r 8 7()
=pri na;tf( " Status:
> :

/*
Y
y

underflow\n", _clear87()
*/

> :
i s 1 enor m al:
154

pri ntf( • status: %. 4x - denormal\n", _clear87() l;


I* y
b = y;
�1

i
.

!
*/

Status:
StaStattus:us: --- denor
Output

00�0
00�0
00�2
clear
i nexact,mal underflow
I

I
155 clearerr

Description Resets the error indicator for a stream.

#include <Stdio.h>

void clearerr( FILE *stream );

stream Pointer to FILE structure

indicator8 are not automatically cleared; once the error indicator for a specified stream is
Rematlls The clearerr function resets the error indicator and end-of-file indicator for stream. Error

set, operations on that stream continue to return an error value until clearerr, fseek,
fsetpos, or rewind is called.

Return Value None.

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

See Also eof, feof, ferror, perror

I***I CLEstrAeaREmR, R.thCe: nThisclearsprogritamsocrtheaattesfuturan eerrorreadsonwon'thetstfail.andard i nput


#include
voi( dintmain{)c; <stdio. h >
putc(Iif(* Crferror(
ea' tce',anstdistdinerrorn >;) by) wri t i ng to standard i nput. */
(
perro r( "Wsrittdienerror•>: );
clearerr(
clearerr l
I

pricif(=nSeeferrtfCgeti1or(("Wstdinri easdtdini causnputecause


s an error.an error?
156

I* � */


n
11 ) ;

perrclea err(r( "Restdiad error•


l ;
1

n
l l
(

I

l ;
� l ;
I
I
I
I

WriWilltei erronput : auseErroanr error? n


Output
I
� 0

157 _clearscreen

Description Clears the specified area of the screen.

#include <graph.h>

void _far _clearscreen( short area );

area Target area

Remarks The _clearscreen function erases the target area, filling it with the current background
color. The area parameter can be one of the following manifest constants (defined in
GRAPH.H):

Constant Action
_GCLEARSCREEN Oears and fills the entire screen
_GVIEWPORT Clears and fills only within the current view port
_GWINDOW Oears and fills only within the current text window

Retum Value None.

Compal/blllty 0 ANSI • DOS • OS/2 0 U NIX · 0 XENIX

See Also _getbkcolor, _setbkcolor

#i#i#i nnnclude
clude <coni o . h >
Exampm ������-

clude <gra
<s t
1 * C L RSC RN . C * /

p
dlih.b h
. >
h >
voi( dshormain()t xhalf, yhalf, xquar, yquar;
struct vi deoconfi g vc;
158

I*
i f(
Fiexi! _ndtse�vi( valideomdode(graphicsMA REmode.MODE
� *I

_gexhalftvi de c.confinumxpig C x&vcels


l
!1 ):
_ X S

f
yhalf yc. n u m y pi x els
>:

xquar fhalf
.
I
= y

yquar half
I
=
2;

1
I
=
r
2;

_setvi e w
_r_elecl ti angpse eCort(GF_GBLLIORDTERIER,xhalxhalfORf xquar
- xhyhala lf f- yquar
- yhalf -
I
=
2;

r
I 2;

- C x quar yhalf - C y quar


0, 0, 1, 1 );

getchCl;
0, 0, 1, 1 >:

_clgetchCearsc eenc _GV IEWPORT


1
_ I N , I 4, I 4,
I 4) , I 4) l ;

r
_setvi de�mode( _DEFAULTMODE
>:

l
I
l :
) ;

I
159 clock

Dncrlpl/on Calculates the time used by the calling process.

#include <time.h>

clock_t clock( void );

Rematks The clock function tells how much processor time has been used by the calling process.
The time in seconds is approximated by dividing the clock return value by the value of the
CLOCKS_PER_SEC constant.

In other words, the clock function returns the number of processor timer ticks that have
elapsed. A timer tick is approximately equal to 1/CLOCKS_PER_SEC seconds.

Return Value The clock function returns the product of the time in seconds and the value of the
CLOCKS_PER_SEC constant. If the processor time is not available, the function returns
the value - I , cast as clock_t.

Compal/bility • ANSI • DOS • OS/2 D UN IX D XENIX

In both DOS and OS/2, clock returns the time elapsed since the process started. This may
not be equal to the actual processor time used by the process.

In previous versions of Microsoft C, the CLOCKS_PER_SEC constant was called


CLK_TCK.

See Also dift'time, time

/**I* then continuousl


C LO C K . C : This exaymdiplespprlayomptss theforelapsedhow longti metheforprograthat mperiisod.to run and
#include
#include <stdi o . h >
#ivoindcludesl eep(<ti mclocke. h>_h>t wait
<s t dli b .
voi( dlongmai n () i >:

clock_t durati
double start , on;fi n i s h;
= 600000 L :
clock

I��!* �Dela�r c y�l ���:for �atr�specified ti m e. */


160

priI* Measu c r * t �� � �K�


ntf( tjDone!e the\durn" a);ti on of an event. */ � ��� � ���->� :
starwhipri n� e(ttf(=i !='rTi-l ock():m) e to do %l d empty loops is i >:
I • ,

durprifi nnaishtitf(o=nr=%clock();
2.C dlouble) ( finish dur- starati ton) ); CLOCK·S_PER_SEC ;
f seconds\n", I

voiI* dPaclockusleep<ses_fbrtil- cgoal:locka s_pecifit waited > number of mi c roseconds. */


l I

goal = �aiboalt +> clock()


while( i
clock(); >
I

Done!TiDelmeay tofordof�ve secondsempty loops is 2. 0 seconds


Output
I
1

�00000
i
I
I
161 close

Description Closes a file.

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

#include <errno.h>

int close( int handle );

handle Handle referring to open file

Rematics The close function closes the file associated with handle.

Return Value The close function returns 0 if the file was successfully closed. A return value of -1 indi­
cates an error, and ermo is set to EBADF, indicating an invalid file-handle argument.

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

See Also chsize, creat, dup, dup2, open, unlink

I**I* OPEN.and aCfile: Thisnamprograed OPEN.m usOeUTs openfor output. to openTha efilefilesnamarede OPEN.then Cclosfored.input
#i#i#i nnnclude
clude
clude <fcntl.
<s
<s y
y s\
s\sta t y h >
pes.
t . h h
> >
#i/voii nnclude
clude <io. h> h>
<stdio.
dintmaifhl,n () fh2 :
{

fhlif( perr=fhlopen(o rC • o" OpenPEN.failed


C ", O_RDONLon inputY ); file"
elsepri ntf( • open succeeded on i nput file\n"
= -1 )
>:

close( fhl ) : >:


close 162

f h 2 = ope p ( " O P E N . OUT " , O_WRON LY I O_C R EAT , S_I READ I S_I W R I T E l :
i f < f h 2 =r - 1 >
p e r r o r ( " open fa i l ed on output f i l e " l :
el se
(
l :
cl ose< I fh2 l :
p r i n t f � " open s u c c eeded on output fi l e \ n "
I

Output
i
I


open s u c c e ed e d on i np u t f i l e
open s uc c e e d d o n o u t p � t f i l e
163 _contro/87

DBBcrlptlan Gets and sets the floating-point control word.

#include <float.h>

unsigned int _control87( unsigned int new, unsigned int mask );

ne w New control-word bit values

mask Mask for new control-word bits to set

Remalb The _control87 function gets and sets the floating-point control word. The floating-point
control word allows the program to change the precision, rounding, and infinity modes in
the floating-point-math package. Floating-point exceptions can also be masked or un­
masked using the _control87 function.

If the value for mask is equal to 0, then control87 gets the floating-point control word. If
mask is nonzero, then a new value for the control word is set in the following manner: for

fpcntrl C C fpcntri I C n ew
any bit that is on (equal to 1 ) in mask, the corresponding bit in new is used to update the
control word. To put it another way,

= & -ma s k ) & ma s k ) )

where f pcntrl is the floating-point control word.

The possible values for the mask constant (mask) and new control values (new) are shown
in Table R. 1 .

Table R.1 Hex Values

Mask Hex Value Constant Hex Value

MCW_EM Ox003F
(lntelTUpt
exception)
EM_INVALID OxOOOl
EM_DENORMAL Ox0002
EM_ZERODIVIDE Ox0004
EM_OVERFLOW Ox0008
EM_UNDERFLOW OxOO I O
EM_INEXACT Ox0020
I

_control,, II
164

I
1 Table R.1 (co11ti11ued)

Mask Hex Value Constant Hex Value

MCW_IC Ox l OOO
(Infinity
contml)
IC_AFFiNE Ox l OOO
IC_PROJECTIVE OxOOOO

MCW_RC OxOCOO
(Rounding
control)
RC_CHOP OxOCOO
RC_UP Ox0800
RC_DOWN Ox0400
RC_NEAR OxOOOO

MCW_PC Ox0300
(Precision
control)
PC_24 (24 bits) OxOOOO
PC_S3 (53 bits) Ox0200
PC_64 (64 bits) Ox0300
i

Return Value
I
l The bits in the value returned indicate the floating-point control state. See the FLOAT.H
I
include file for a complete definition of the bits returned by _control87.
I
Campal/blllty i
I
D ANSI 8 DOS • OS/2 D U N IX D XENIX

See Also _clear87, _status87

Exampm
1* CNseTtRLthe87. recisi
----����-


f
: Thisoprogra n to m biusetss,_canodntrroels8et7 totheoutputstatustheto thcontrole defaulwortd. ,
//ttii ncncl udeude <s<f dioaot .. hh>>
* 24
*I ,
!
1 t
)
I
t

I I
!
_contro/87

voi ddoublmai ne ()a 0. 1 ;


165

g1. li nfal*l %1.control


I*pripri nnShtf(tf(ow ori""O%rigina l 8a,7( a 0,* 0a on.);) ) */:
and doa,ocalculati
: 0x%.lf 4x\n",wor%. 1d5e\n",_contr
=

""%241.-bil fto*n: %1.to0x%.24lf 4bix\n",%.ts 1and5e\_control


pripriI* nnSettf(tf( precisi rn",ecala, c8a,ulate.7( a P*C_*/a24 );, MCW_PC ) ) :
=

t* : %1.0x%.lfand4x\%.nre1",calcula
pripriI* nnRetf(tf(store"" %Defaul1.tolfdefault
=

=
t e. */
5e\n", a, a,7( aCW*_aDEF);AULT , 0xffff ) );
_contr o l 8
0.0.Ori24-11gb**it:i n0.0.al:11 0x10x19.1.3303293200000000000000e- 0 02
Output

Default:
=

0x1
0. 1 * 0. 1 1. 000000000000000e-002
=

=
0 32 999997764825 8 2e- 0 03
cos Funct ans f 166

Description Calculate the cosine (cos and cosl) or hyperbolic cosine (cosh and coshl).

#include <math.h>

double cos( double x ) ;


double cosh( double x );
long double cosl( long double x );
long double coshl( long double x ) ;

x Angle in radians

Remarks The cos and cosh functions return the cosine and hyperbolic cosine, respectively, of x.

The cosl and coshl functions are the 80-bit counterparts and use the 80-bit, 10-byte co­
processor fonn of arguments and return values. See the reference page on the long double
functions for more details on this data type.

Return Value If x is large, a partial loss of significance in the result may occur in a call to cos, in which
case the function generates a PLOSS error. If x is so large that significance is completely
lost, cos prints a TLOSS message to stderr and returns 0. In both cases, errno is set to
ERANGE.

If the result is too large in a cosh call, the function returns HUGE_VAL and sets errno to
ERANGE.

Compallblllty cos, cosh

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

cosl, coshl

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


161 cos Functions

S1111 Alsa acos functions, asin functions, atan functions, matherr, sin functions, tan functions

I*I** and hyperbThisolic cosiprogranemofdi pisplaIy2.s the si ne, hyperboli c si ne, cosi ne,
S I N C OS . C :

#i#i nnclude
clude <<smath.tdi oh. >h>
voi( ddoublemai n ()pi = 3. 1415926535;
double x, y;
yyxpri===npisisitf(nnIhC( " xs2;xi n);(>: %f ) = %f\n", x, y );
pripri nntf(tf( "• scos(i n) h( %f%f ) )==%f\n"%f\n",, x,x , yy );>:
ypri=ncoshCtf( "cxosh(>: %f > = %f\n " , x , y >;
Y = COS ( X ;

sicosh(si nnhC( 1.1.1.1.557575007700779977966966 >) >>====0.1.2.2.0000000


350091129978
Output

COS ( 00000
cprintf 168

Description Formats and prints to the console.

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

int cprintf( char *format [, argument] ... );

format Format control string

argument Optional arguments

Remarks The cprintf function formats and prints a series of characters and values directly to the
console, using the putch function to output characters. Each argument (if any) is con­
verted and output according to the corresponding format specification informat. The for­
mat has the same form and function as theformat argument for the printf function; see
printf for a description of the format and arguments.
Note that unlike the fprintf, printf, and sprintf functions, cprintf does not translate line­
feed characters into carriage-return-line-feed combinations on output.

Return Value The cprintf function returns the number of characters printed.

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

See Also cscanf, fprintf, printf, sprintf, vprintf

CPRI N TF.
#ivoindcludemai n<c ni o . h>
I*

p
C : This progra m di s pla y s s o m e vari a bles to the cons o l e . */

unsicharchari nt gned' cuis[==J ' A "';Tesht=" ;


( )!
I

(
= -16 , 29 ;
625 1 1 ;

=
cprinff

Notestandarthatd output
consoledoes.outputUsedoes\r\nnoti nsttransla te \n as
169

cprintfC " %d %. 4x %u %c %s\r\n", i, h, u, c, s


I*
*
*I
ea d . l ;

Output

-16 00ld 6251 1 A Test


cputs 170

OBSctlpUon Puts a string to the console.

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

int cputs( char *string );

string Output string

Remarks The cputs function writes the null-tenninated string pointed to by string directly to the con­
sole. Note that a carriage-return-line-feed (CR-LF) combination is not automatically ap­
pended to the string.

Return Value If successful, cputs returns a 0. If the function fails, it returns a nonzero value.

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

See Also putch

I#i*nclude <co�hisi o . hpr> ogram first displays a string to the console. */


Exampm __ -+--------------------------------------------------------�

C P UTS . C :


voi dI*maiStnring() to pri nt at console. Note the \r ( return } character. */
i
i
{

charcputs(*bufbu erfer� };" Hello worl d ( courtesy of cputs}! \ r\n":


i

!

I
r
I

°*'
I

Hello worl d f courtesy of cputs}!


171 creat

Description Creates a new file.

#include <Sys\types.h>
#include <Sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations

int creat( char *filename, int pmode ) ;

filename Path name of new file


pmode Permission setting

Remarks The creat function either creates a new file or opens and truncates an existing file. If the
file specified by filename does not exist, a new file is created with the given permission set­
ting and is opened for writing. If the file already exists and its permission setting allows
writing, creat truncates the file to length 0, destroying the previous contents, and opens it
for writing.
The permission setting, pmode, applies to newly created files only. The new file receives
the specified permission setting after it is closed for the first time. The integer expression
pmode contains one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SY�TAT.H. When both of the constants are given, they are joined with the bitwise-OR
operator ( I ). The pmode argument is set to one of the following values:

Value Meaning
S_IWRITE Writing permitted
S_IREAD Reading permitted
S_IREAD I S_IWRITE Reading and writing permitted

If write permission is not given, the file is read-only. Under DOS and OS/2, it is not
possible to give write-only permission. Thus, the S_IWRITE and S_IREAD I S_IWRITE
modes are equivalent. Under DOS versions 3.0 and later, files opened using creat are al­
ways opened in compatibility mode (see sopen).
The creat function applies the current file-permission mask to pmode before setting the
permissions (see umask).
Note that the creat routine is provided primarily for compatibility with previous libraries.
A call to open with 0_CREAT and 0_TRUNC in the oflag argument is equivalent to creat
and is preferable for new code.
creat 172

Return Value If successful, creat returns a handle for the created file. Otherwise, it returns -1 and sets
errno to one of the following constants:

Value Meaning
EACCES Path name specifies an existing read-only file or specifies a
directory instead of a file
EMFILE No more handles available (too many open files)
ENOENT Path name not found

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

See Also chmod, chsize, close, dup, dup2, open, sopen, umask

/* CREexistiAT. Cng: �hislfil e ) progranamedmdausteas andcreatopento itcrforeatewritithe fileng. < or truncate the
#i#i#i nnnclude <s y lss\\ts ytapes. h >
*

clude I
<s y t . h >
*I

#i#i nnclude
clude
clude \

<io
<st
<st . h
i
li>
ob. h. >h>
voi( di nmait fh:n ()
r
I

i
) ata", tS_crIREeaAtDe dataS_I WfilRITeE" );
fhif( perrfhcreoar{�1 C " C" douldn'
j
I

elsepri ntfiC " C reated data fil e . \ n"


=
== - 1
>:

(
cl ose< fh !
1

I
>:
>:
I
I

Created data fil e .


Output
173 cscanf

Dut:r/pllan Reads formatted data from the console.

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

int cscanf( char *format [, argumentD ... );

format Format-control string


argument Optional arguments

Remam The cscanf function reads data directly from the console into the locations given by
argument. The getche function is used to read characters. Each optional argument must be
a pointer to a variable with a type that corresponds to a type specifier in format. The for­
mat controls the interpretation of the input fields and has the same form and function as the
format argument for the scanf function; see scanf for a description offormat.
While cscanf normally echoes the input character, it will not do so if the last call was to
ungetch.

Return Value The cscanf function returns the number of fields that were successfully converted and as­
signed. The return value does not include fields that were read but not assigned.
The return value is EOF for an attempt to read at end-of-file. This may occur when key­
board input is redirected at the operating system command-line level. A return value of 0
means that no fields were assigned.

Campal/bll/ty D ANSI • DOS • OS/2 D UNIX D XENIX

See Also cprintf, fscanf, scanf, sscanf

inandthetheresprograThiponse.smprogra
I * C S CAN F . C :
* Thdispenlamycsprscathonmfptsat returns
fornumber.a thstringe numandber ofusesi tcscanf
ems mattoched,read
#i#i nnclude
clude <stdi<conio.o . hh>>
*
*I
'

voi di nmait n r()e I ult, i[3J;


cscanf 174

I
{ :

cpricprintf(
result ntf(=1cscanf(
f
"E" \nr\ternYouthr" %enterei e%iintegers:
I
I

e %i",
d • &i[
); "):
0 J, &i[ l ], &i[ 2 ] ) ;
while( nrt
sult-
f<
1
" % -
i )
cprintf( " \ r\n" ) ; i[resul t J.>;
cpri ",
I

YouEnterenterthreede integers:43 34 34 43
Output

987 k
987
175 clime

Descrlpllan Converts a time stored as a time_t value to a character string.

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

char *ctime( const time_t *timer );

timer Pointer to stored time

Rematits The ctime function converts a time stored as a time t value to a character string. The
timer v alue is usually obtained from a call to time, which returns the number of seconds
elapsed since 00:00:00 Greenwich mean time, January 1 , 1 970.

Wed Jan
The string result produced by ctime contains exactly 26 characters and has the form of the
following example:

02 02 : 03 : 5 5 1 980 \ 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.

Calls to the ctime function modify the single statically allocated buffer used by the
gmtime and the localtime functions. Each call to one of these routines destroys the result
of the previous call. The ctime function also shares a static buffer with the asctime func­
tion. Thus, a call to ctime destroys the results of any previous call to asctime, localtime,
or gmtime.

Retum Value The ctime function returns a pointer to the character string result. If time represents a date
before 1 980, ctime returns NULL.

Campallbil/ty • ANSI • DOS • OS/2 • U N IX • XENIX

S11 Alsa asctime, ftime, gmtime, localtime, time

I*
*
ASCTItransl
M E.
a C
tes: This
i t i n progra
to the m s pla
t c es
ructurethe
ne s
w y
ti
stri ng form for output, usi ng the ascti me functi on. s t
m e
e m ti
and m e i
thenn the long
converts i
i n
t teger
to aclock,
#i#i nnclude
clude <ti<stdime.oh. >h>
*
*I
clime

tivoistructmde_mait aclotmn ( *ne) ! k;wti me;


176


!

(
tinemwe(ti m&ae locklocalti); me( &aclock ); //** GetConvertti metiinmesetoconds.struct*/ tm form . */

I

pri/ * nPritf(nt Thlocale currti meentasdatea striandng.ti m*/e are : %s\n", ascti me( newti me ) );
f
!

The current date and ti me are : Thu Jun


Output

!
I
!
1 5 0 6 : 5 7 : 5 9 1 989
177 cwait

DBScr/pllon Waits until the child process tenninates.

#include <process.h>

int cwait( int *termstat, int procid, int action );

termstat Address for tennination status code


procid Process ID of child
action Action code

Rematks The cwait function suspends the calling process until the specified child process
tenninates.

If not NULL, termstat points to a buffer where cwait will place the tennination-status word
and the return code of the tenninated child process.

The tennination-status word indicates whether or not the child process tenninated nor­
mally by calling the OS/2 DosExit function. (Programs that terminate with exit or by
"falling off the end of main" use DosExit internally.) If the process did terminate nor­
mally, the low-order and high-order bytes of the tennination-status word are as follows:

Byte Contents

High order Contains the low-order byte of the result code that the child
code passed to-DosExit. The DosExit function is called if the
child process called exit or _exit, returned from main, or
reached the end of main. The low-order byte of the result
code is either the low-order byte of the argument to _exit or
exit, the low-order byte of the return value from main, or a
random value if the child process reached the end of main.
Low order 0 (normal tennination).
cwait 178 !

If the child process terminates without calling DosExit, the high-order and low-order bytes
of the termination-status word are as follows:

Byte Contents

High order 0
Low order Termination code from DosCWait:

Code Meaning

Hard-error abort
2 Trap operation
3 SIGTERM signal not intercepted

The procid argument specifies which child-process termination to wait for. This value is re­
turned by the call to the spawn function that started the child process. If the specified child
process terminates before cwait is called, the function returns immediately.
The action argument specifies when the parent process resumes execution, as shown in the
following list:

Value Meaning

WAIT_CHILD The parent process waits until the specified child process has
ended.
WAIT_GRANDCHILD The parent process waits until the specified child process and
all child processes of that child process have ended.

The WAIT_CHILD and WAIT_GRANDCHILD action codes are defined in PROCESS.ff.

Return Value! If the cwait function returns after normal termination of the child process, it returns the
child's process ID.
If the cwait function returns after abnormal termination of the child process, it returns -1
and sets errno to EINTR.
Otherwise, the cwait function returns - 1 immediately and sets errno to one of the follow­
ing error codes:

Value Meaning

ECHILD No child process exists, or invalid process ID


EINVAL Invalid action code
179 cwait

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

Note that the OS/2 DosExit function allows programs to return a 1 6-bit result code. How­
ever, the wait and cwait functions return only the low-order byte of that result code.

See Also exit, _exit, spawn functions, wait

I*I** CWAIfor Ta . Csp: ecifie This dprograprocessm launchto fiesn i severals h. child processes and waits
#defi#define
#defi nnee III NNNCLCLCL___DNNOOOCOMMON
PSPRM OCESS
#i#i#i nnnclude
clude
clude <os2.
<pr
<stdli o h
cess. >
b . h h
> > /*
/ * Dos
c w S
ai l
t e ep */
*/
#i#include
nclude <stdi<ti me.oh. >h>
I* Macrneogetrato getndom(a raminndo, mmai xnteger) ((rwia nd()thi n a ( si pnt){((eci fi medaxra) nge1) */- ( mi n ))) ( mi n ))
#defistruct
( charint CHILpinaD mde[; 10];
% + +

chil d [ 4 ] ( 0, " A nn"


voi( dintmai n ( inttermarstgc,at , charpi d , *arc, gtv[Jmp;
= ( J, ( J, 0, " B eth" ( 0, "
J, C arl• ( 0, " D ave"
I I;

srIif*aC nIdCafrgcnoC uarnsiggu1mneents,ld l t i mthiseC NULLis the) l; parent. */ I* Seed randomizer */


( I*foreSpacwn chil0; cd<ren4; i c++n numeri c order. */
==

chil d [c]. pi d spawnl( chilP_NOWAId [ cT]., narame,gv[0NULL], arl;gv[0],


=
l
cwan

cpric/*wa tCtfCgetraai t&terfor"nCdom(memstat,ra ndohere,0, mlchild[


y%s\n",specifichiled dchild,[ c J. nameand respond when done. */
180

pri tf( "Thank you, %s\nc",]. pchili d , dWAI[ c J.T_naCHILme D


3 );
o
=

>:
>:

elI*seI fI*t ereel ayarfore aragperiuments,od deterthismmusinedt beby aproceschi l ds . nu*/mber. */


>:

priDosltf(leep("Hi,C a rdad.gv[1][I 0t J' s -%s.' A\' n", 1ar) *gv[l]1000L); );


(

�ComeHi,Hi, dad.dad.here,II ttjl arlss Ann.Beth.


ThHi,Hi,a nkdadayou,dd .. I! ttisars Carl.Dal ve.
'
181 dieeetomsbin, dmsbintoieee

0118Ctlpnan Convert between IEEE double value and Microsoft (MS) binary double value.

#include <math.h>

int dieeetomsbin( double *srcB, double *dstB );

int dmsbintoieee( double *srcB, double *dstB );

srcB Buffer containing value to convert

dstB Buffer to store converted value

Rematks The dieeetomsbin routine converts a double-precision number in IEEE (Institute of


Electrical and Electronic Engineers) format to Microsoft (MS) binary format. The routine
dmsbintoieee converts a double-precision number in MS binary format to IEEE format.

These routines allow C programs (which store floating-point numbers in the IEEE format)
to use numeric data in random-access data files created with those versions of Microsoft
BASIC that store floating-point numbers in MS binary format, and vice versa.

The argument srcB is a pointer to the double value to be converted. The result is stored at
the location given by dstB.

These routines do not handle IBEE NANs ("not a number") and infinities. IBEE denormals
are treated as 0 in the conversions.

Return Value These functions return 0 if the conversion is successful and 1 if the conversion causes an
overflow.

CampaNblllty 0 ANSI • DOS • OS/2 0 U N IX 0 XENIX

See Also fieeetomsbin, fmsbintoieee


difftim 182

Dest:rlptlon Finds the difference between two times.

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

double difftime( time_t timerl , time_t timerO );

timerO Beginning time

timer] Ending time

Remarks The difftime function computes the difference between the supplied time values, timerO
and timerl.

Return Value The difftime function returns, in seconds, the elapsed time from timerO to timerl . The
value returned is a double-precision number.

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

See Also time

do a fl ati nThisg-poi progra


I
I * D I F FT I M � . C :
nt mul mtiplcalyculatestithemes.amount of ti me needed to
#i#i#inclnnclude
cludeude <<< tdio.tdlii me. bh>h. >h>
* 50000
*I

voi( dti maime_nt ( start , fi nish;


uns i gne resoop:ul t , el a psed_ti me;
double I

pripri nntf(tf( ""TWorkihis progra m wi);l l do a fl oati ng poi nt mul tipl y ti mes\n" );
1

n g ... \n"
tifor(me(reslo&ujl tartp ==t ); loop < loop++ )
50000

time & ini sh ) ;


C
0; 50000 L ;
3 . 63 * 5 . 27 ;

I
difflime

priel a npsetfCd_ti"\mneProgradi mfftakt i meeCs %6.fi n2ish,f seconds.


start \n", el a psed_ti me
183

= >:
>:

WorkiThisProgranprogra
gm takesm will do aseconds.
fl oati ng poi nt mul t i p l y ti mes
Oulput

50000
• • •

4 . 00
_disable!
II

184

_,,,,,. I Disables interrupts.

I #include <dos.h>

void _disable( void );

Remarks The _disable routine disables interrupts by executing an 8086 CLI machine instruction.
Use _disable before modifying an interrupt vector.

Retum Value None.

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

See Also _enable


185 _disp/aycursor

Description Sets the cursor toggle for graphics functions.

#include <graph.h>

short _far _displaycursor( short toggle );

toggle Cursor state

Remarks Upon entry into each graphic routine, the screen cursor is turned off. The _displaycursor
function determines whether the cursor will be turned back on when programs exit graphic
routines. If toggle is set to _GCURSORON, the cursor will be restored on exit. If toggle is
set to _GCURSOROFF, the cursor will be left off.

Return Value The function returns the previous value of toggle. There is no error return.

Campal/bl/lty D ANSI • DOS • OS/2 D UNIX D XENIX

BBB Also _gettextcursor, _settextcursor

/*· */* andDI SCUR_seStte. C : xThistcursor,prograanmd changes


hi des thethecurscursoror usishapeng _diusisplangy_gettextcursor
cursor.
#i#include
nclude <coni<graph.o . hh>>
voi( dshortmain()ol dcursor:
short
I*dcursor ne w cursor
Savsecroleden(_gett 0x007;
curs_GCoerLxtcursor();
shape and mak I
e * Full
sur e block
cursor cursor
i s on */ */
ol_clear
=

_displa
_outtext(
=

y cursor( _G E
C A RSCREEN
URSOR O N
" \ nOl d cursor shape: " ); );
);
getchCl;
I_sette
* Changextcursor(cursor shanewcursor
pe */sha);pe:
_outtext(
getchC); " \ nNe w cursor " > :
R_setteestx,cursorC
Cre "\orin " g i);nolaldcursor
cursor shape
186

_outtex
/*

> ;
*/
187 div

Description Computes the quotient and the remainder of two integer values.

#include <Stdlib.h>

div_t div( int numer, int denom );

numer Numerator
denom Denominator

Remarks The div function divides numer by denom, computing the quotient and the remainder. The
div_t structure contains the following elements:

Element Description

int quot Quotient


int rem Remainder

The sign of the quotient is the same as that of the mathematical quotient. Its absolute value
is the largest integer that is less than the absolute value of the mathematical quotient. If the
denominator is 0, the program will terminate with an error message.

Return Value The div function returns a structure of type div_t, comprising both the quotient and the re­
mainder. The structure is defined in STDLIB.H.

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

See Also ldiv

I*** twodisplaarygThisuments
Example

s the exaresults
monplethetakcoofmemanthes twdoi nliteger
i nnteger
__________________________________________________________________�

s as
divisi oco
n. m mand-line
This pr o ar
gr a g
m u m ents
accepts a n d
first arquotegumentfollandowbyi nrethegm.thesecond.programFi nanallme,y , then
**/* callsit pri divnts theto divistrduecturethe members
DIV .C:

#i#i#i nnnclude
clude <stdli
<stdio.
clude <math. h> b .
h h
> >
voi di nmait x,ny<[ : int argc, char *argv[J
divx =_tatod\lii v(_arregsult;v[l] );
l
{ .
l

=pri natoi(tf( • xarisgv[%d,2] y is %d\n", x,


diprintfCv_resuldiv"Tthe_=resdiquotient
vul( tx,. quot,yis div%d,_aresnduthel t . rermemai nder is %d\n",
y l:
'

y l :
l:

l:

xThe[ Cis: \quotiLI BREFe�1 tdivisis and the remai nder is


Output
I

876 13
876 , 13
67 , 5
189 _dos_allocmem

De1t:rlplion Allocates a block of memory, using DOS service Ox48.

#include <dos.h>

#include <errno.h>

unsigned _dos_allocmem( unsigned size, unsigned *seg );

size Block size to allocate


seg Return buffer for segment descriptor

Remarks The dos allocmem function uses DOS service Ox48 to allocate a block of memory size
paragraphs long. (A paragraph is 1 6 bytes.) Allocated blocks are always paragraph
aligned. The segment descriptor for the initial segment of the new block is returned in the
word that seg points to. If the request cannot be satisfied, the maximum possible size (in
paragraphs) is returned in this word instead.

Retum Value If successful, the dos allocmem returns 0. Otherwise, it returns the DOS error code and
sets errno to ENOMEM, indicating insufficient memory or invalid arena (memory area)
headers.

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

See Also alloca, calloc functions, _dos_freemem, _dos_setblock, halloc, malloc functions

I**I* the all ocati Thison toprograparma alloca


DALOCMEM . C :
graphs,tesand thparaen frees
20 graphsthofe memor
memoryy , spi nacrce.eases
#iIvoii nncdcludemaiuden<stdi<dos.() oh>. h>
40

( unsigned unsigned masegment: xsi ze:


d
_ os_a�/ocmem
I
ielsef ( Allopri_don�_allo
af(te " acllocati
mem(paragroanphs&segment
190

/* 20 */

failed\n" ) );
priI n ern asef( " aallocation
llocati on tosuccessful\n" );
20 , != 0

if(elsepri_don _setblock(
I*

f(f( "" aallocation 40


seg
incr m e para
ent,
ase & g
m r a
axsip
failed\n" hs
*/
ze ) );
llocati o n i n cr e as e s u cces s f ul\n" );
40 , != 0

ielsef ( freepri_don _frmemor


I*
ef( "efymrem(ee memorsegmeny tfailed\n"
*/
) );
pri n f( " free memory successful\n" );
!= 0 >

allocation
free memor i nsuccessful
allocati
Output

o n successful
crease successful
191 _dos_ close

Dest:rlpllan Closes a file using system call INT Ox3E.

#inclu.de <dos.h>

#include <errno.h>

unsigned _dos_close( int handle );

handle Target file handle

Rematks The _dos_close function uses system call Ox3E to close the file indicated by handle. The
file's handle argument is returned by the call that created or last opened the file.

Return Value The function returns 0 if successful. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating an invalid file handle.

Do not use the DOS interface 1/0 routines with the console, low-level, or stream 1/0
routines.

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

See Also close, creat, _dos_creat functions, _dos_open, _dos_read, _dos_write, dup, open

I*#i nDOPEN.
Exampm
C : This progra m us e s DOS
_________________________________________________________________

I/ O functions t o open and clos e a fi l e. */


#i/Ii nnclclude
cludeude <fcntl.<stdi<dos. oh>. hh>>
voi( dintmaifh;n ()
I*if( Openperr_doso_filer(open(" Owipent"dhatal",
_dosfailed_openOo_n RDi funcnOputNLYt, file\ion&fh*/n "
elsepri ntf( " Open succeeded on i nput fi l e\n" > != 0
> :
>

>:
if(el sClperre_doos1_closrfile( " CelosewiC tfhhfailed\n"
_dos_close functi �n
192

I
'
!= 0
/* */

pri n f( " File successfull y closed\n"


l l
l ;

l ;

OpenFile succe
Output

succe dedsfulloyn closed


I
I

input file
193 t
_das_crea Functions

Description Create a new file.

#include <dos.h>

#include <errno.h>

unsigned _dos_creat( char *filename, unsigned attrib, int *handle );

unsigned _dos_creatnew( char *filename, unsigned attrib, int *handle );

filename File path name


attrib File attributes
handle Handle return buffer

Remarks The _dos_creat and _dos_creatnew routines create and open a new file namedfilename;
this new file has the access attributes specified in the attrib argument. The new file's
handle is copied into the integer location pointed to by handle. The file is opened for both
read and write access. If file sharing is installed, the file is opened in compatibility mode.
The _dos_creat routine uses system call INT Ox3C, and the _dos_creatnew routine uses
system call INT Ox5B. If the file already exists, _dos_creat erases its contents and leaves
its attributes unchanged; however, the _dos_creatnew routine fails if the file already exists.

Return Value If successful, both routines return 0. Otherwise, they return the DOS error code and set
errno to one of the following values:

Constant Meaning

EACCES Access denied because the directory is full or, for _dos_creat
only, the file exists and cannot be overwritten
EEXIST File already exists (_dos_creatnew only)
EMFILE Too many open file handles
ENOENT Path or file not found
II
_dos_c at Functions � 194

Compallblllty I
I

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


!

DCREbecaAuseT.mCi annot
** progra eadyatexiemastcrs.neewatesfilea filusi engusingthe _dosthe__doscrea_tcrneweatfunctifunction.on The
Thit alrs ecrprogra
Exampm �-+-�����
I* j
s
l

#i#i/fi nnncclude
*I

cludeude <s<s<d didlib.s. oh>. h>h>



1

,

voi dintmaifhl,n () fh2;


1

I
I

intif( _dosresulltcr; eat( "data", _A_NORMAL, &fhl )


i

(
elsepripri nntt1'(( ""CCouldn'

r e a t ed
t create data fil e\n"
data fil e . \ n " );
>:
!= 0

wii f ( If_dl _doslos_failcr_creaeatnesi tnwceis( th"dsuccessful, the _dos_creatnew call


I

I*
* h eata•,fi l e_Aexists
_ RD O NL Y , &fh 2
elsepri,ntf( " C reated data fil e . \n" );
pri � tf( " C oul d n' t create data file\ n "
*I I
) != 0 )

I
_do 1 s
_dos_cll ose( fhl _ cl ose(

fh2 )
>;
:
>:

I
CrCouldn'eatedtdatacre tefil edata. file I
I

Output

Lr
i
195 _ dos_ find Functions
Description Find the file with the specified attributes or find the next file with the specified attributes.

#include <dos.h>

#include <errno.h>

unsigned _dos_findfirst( char *filename, unsigned attrib, struct find_t *fileinfo );

unsigned _dos_findnext( struct find_t *fileinfo ) ;

filename Target file name

attrib Target attributes

fileinfo File-information buffer

Remarks The _dos_findfirst routine uses system call INT Ox4E to return information about the first
instance of a file whose name and attributes match filename and attrib.

Thefllename argument may use wildcards {* and ?). The attrib argument can be any of the
following manifest constants:

Constant Meaning

_ A ARCH
_ Archive. Set whenever the file is changed, and cleared by the
DOS BACKUP command.

_ A HIDDEN
_ Hidden file. Cannot be found with the DOS DIR command.
Returns information about normal files as well as about files
with this attribute.

_A NORMAL
_ Normal. File can be read or written without restriction.

_A RDONLY
_ Read-only. File cannot be opened for writing, and a file with
the same name cannot be created. Returns information about
normal files as well as about files with this attribute.

_A SUBDIR
_ Subdirectory. Returns information about normal files as well
as about files with this attribute.

_A SYSTEM
_ System file. Cannot be found with the DOS DIR command.
Returns information about normal files as well as about files
with this attribute.

_A VOLID
_ Volume ID. Only one file can have this attribute, and it must
be in the root directory.
_dos_fin Functions 196

Multiple constants can be combined (with the OR operator), using the vertical-bar ( I )
character.

If the attributes argument to either of these functions is _A_RDONLY, _A_HIDDEN,


_A_SYSTEM, or _A_SUBDIR, the function also returns any normal attribute files that
match thefilename argument. That is, a normal file does not have a read-only, hidden, sys­
tem, or directory attribute.

Information is returned in a find-t structure, defined in DOS.ff. The find t structure con-
tains the following elements: -

Element Description

char reserved[21] Reserved for use by DOS

char attrib Attribute byte for matched path

unsigned wr_time Time of last write to tile

unsigned wr_date Date of last write to file

long size Length of file in bytes

char name[13] Null-terminated name of matched file/directory, without


the path

The formats for the wr time and wr date elements are in DOS format and are not usable
by any other C run-time function. The time format is shown below:

Bits Contents

0-4 Number of 2-second increments (0- 29)

5 -10 Minutes (0- 59)

1 1-15 Hours (0- 23)

The date format is shown below:

Bits Contents

0-4 Day of month (1-3 1 )

5-8 Month (1-12)

9-15 Year (relative to 1980)

Do not alter the contents of the buffer between a call to dos findfirst and a subsequent
call to the dos findnext function. Also, the buffer shoUtd not be altered between calls to
_dos_findiiext-
197 _ dos_ find Functions
The _ dos_findnext routine uses system call Ox4F to find the next name, if any, that
matches the filename and attrib arguments specified in a prior call to _dos_findfirst The
fileinfo argument must point to a structure initialized by a previous call to _dos_findfirst
The contents of the structure will be altered as described above if a match is found

Return Value If successful, both functions return 0. Otherwise, they return the DOS error code and set
errno to ENOENT, indicating that filename could not be matched.

Compatibility 0 ANSI • DOS 0 OS/2 0 U NIX 0 XENIX

I**I DFItheND..cCextensi : This pron.ogram fi nds and prints all files i n the current directory wi th
#iIi nnccludeude <stdio. h>
*

<dos.
mai( nstr() uct fi nd_t c_file;
1 h >
_dosI*pri nfi_tf(nfidnfirst
dfirst< . c " *file. c ", i _An _currNORMentAL , dir&c_efilectory */
printf( "Listi ng%sofis .c%ldfi bl yes\n\n"
"File: tes\n",
>:

);c_fil e . name, c_file. s ize


I* prifi ndn_dostf(the_"Ffirei nle:stdnext(of%stheis&c_%l. cfiledfilesbytes\n",
while( � 0 ) ) */ c_fi l e . name, c_fil e . s i ze
> :

>:

LiFile:sti nCHDIg ofR .. Cc filesis bytes


Output

File:File:File: MAX.CGESI GTFP.CS. CCis isis bytesbybytestes


524

Fi l e: FWRITE. C is bytes
2674
258
577
1 123
,
I

_ dos f msm
_ 198

Description Releases a block of memory (INT Ox49).

#include <dos.h>

#include <errno.h>

unsigned _dos_freemem( unsigned seg );

seg Block to be released

Rematics The _dos_freemem function uses system call Ox49 to release a block of memory pre­
viously allocated by _dos_allocmem. The seg argument is a value returned.by a previous
call to _dos_allocmem The freed memory may no longer be used by the application
program.

Return Value If successful, dos freemem returns 0. Otherwise, it returns the DOS error code and sets
errno to ENOMEM, indicating a bad segment value (one that does not correspond to a seg­
ment returned by a previous _dos_allocmem call) or invalid arena headers.

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

S1111 Alsa _dos_allocmem, _dos_setblock, free functions

I * DA LOCMEM . : T h i s p r o g r a m a l l o c a t e s 20 pa ra g ra p h s of memo ry , i n c rea s e s


* t h e a l l oc t i on t o 40 p a r a g r a p h s , a n d t h e n frees t h e memo ry s p a c e .
*I


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

I
t
v o i d ma i n ( )

f egment :
(
u n s i g n ed
u n s i g n ed axs i ze :

/ * Al l o c a e ?0 pa r a g r a p h s * /
i f ( _d os_ l l o cmem C 20 , & s egment J ! = 0
p r i n t f " a l l o c a t i on fa i l ed \ n " l :
el se
p r i n t f " a l l oc a t i o n s u c c e s s fu l \ n " l :
dos freemem
*/
199 _ _

!= 0
I * I n c re a s e a l l oca t i o n t o 40 p a r a g r a p h s
i f ( _do s_s e t b l o c k C 40 , s egmen t , &ma x s i ze )
p r i n t f ( " a l l oc a t i on i n c rea s e fa i l ed \ n " ) ;
el se
p r i n t f C " a l l oca t i o n i n c rea s e s uc c e s s f u l \ n " ) ;

!=
I * Free memo ry * I
i f ( _do s_f reemem ( s egment ) 0 )
p r i n t f ( " f ree memo ry fa i l ed \ n " ) ;
el se
p r i n t f C " f ree memo ry s u cc e s s fu l \ n " ) ;

Output

a l l o c a t i on s u c c e s s fu l
a l l o c a t i on i nc re a s e s u c c e s s f u l
f ree memo ry s u c c e s s f u l
I
I
_ das g tdate
_ 200

Oescr/pl/an Gets current system date using system call INT Ox2A.

#include <dos.h>

void _dos_getdate( struct dosdate_t *date );

date Current system date

Rematb The _dos_getdate routine uses system call Ox2A to obtain the current system date. The
date is returned in a dosdate_t structure, defined in DOS.ff.

The dosdate_t structure contains the following elements:

-
Element Description

unsigned char day 1-3 1


unsigned char month 1-12
unsigned int year 1980-2099
unsigned char dayofweek 0-6 (0 = Sunday)

Return Value None.

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

S11 Also _dos_gettime, _dos_setdate, _dos_settime, gmtime, localtime, mktime, _strdate,


_strtime, time

&ampm -+---------------------------------------------------�------

DGTIME . CI: T h i s p ro g r a m
___

r
I* gets a n d d i s p l a y s c u r r ent d a t e a n d t i me v a l ues . * /

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


Ii i n c l u d e < d s . h >

v o i d ma i n ( )


{

l
I
s t r u c t d s d a t e_t d a t e ;
s t ru c t d s t i me_t t i me ;

I
201 _ das getdate
_

I * Get c u r re n t d a t e a n d t i me v a l ues * /

_d o s_g etd a t e ( &da t e } ;


_d o s_g et t i me ( & t i me } ;

p r i n t f ( " T o d a y ' s d a t e i s % d - %d - %d \ n " , d a t e . mo n t h , d a t e . d a y , d a t e . y e a r ) ;


p r i n t f ( " T h e t i me i s %02d : %02 d \ n " , t i me . ho u r , t i me . mi n u t e } ;

Output

Today ' s d a t e i s 6 - 1 5 - 1 989


The t i me i s 1 8 : 07
_das_ge disldree 202

DelCflptlon Gets disk information using system call INT Ox36.

#include <dos.h>

#include <errno.h>

unsigned _dos_getdiskfree( unsigned drive, struct diskfree_t *diskspace );

drive Drive number (default is 0)

diskspace Buffer to hold disk information

Remades The _dos_getdiskfree routine uses system call Ox36 to obtain information on the disk
drive specified by drive. The default drive is 0, drive A is 1 , drive B is 2, and so on.
Information is returned in the diskfree_t structure (defined in DOS.H) pointed to by
diskspace.
The struct diskfree�t structure contains the following elements:

Element Description

unsigned total_clusters Total clusters on disk


unsigned avail_clusters Available clusters on disk
unsigned sectors_per_cluster Sectors per cluster
unsigned bytes_per_sector Bytes per sector

Retum Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets ermo to
EINV AL, indicating that an invalid drive was specified.

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

See Also _dos_getdrive, _dos_setdrive

/ * DGD I S K F R . C : T h i s p r o g r a m d i s p l a y s i n f o rma t i on a bout t h e defa u l t d i s k d r i v e . * /

t
#i n c l u d e < s t d i o . h>
Ii i n c 1 ude < d . h >

I
I
203 _ dos getdiskfree
_

ma i n ( )
(
s t ruct d i s k f r e e_t d r i v e ;

I * Get i n fo rma t i on on d e fa u l t d i s k d ri v e 0 * /

_d o s_g etd i s k free ( 0 , &d r i v e > :


p r i ntf ( " t ot a l c l u s t e r s : %d \ n " , d r i v e . t o t a l _c l u s t e r s ) ;
p r i n t f ( • a v a i l a bl e c l u s t e r s : % d \ n " , d r i v e . a v a i l _c l u s t e r s > :
p r i n t f ( " s ec t o r s p e r c l u s t e r : % d \ n " , d r i v e . s e c t o r s_p e r_c l u s t e r > :
p r i n t f ( " by t e s per s e c t o r : % d \ n " , d r i v e . byt e s_pe r_s e c t o r > :

Output

tota l cl usters : 9013


a v a i l a b l e c l u s t e r s : 6030
sectors per c l uster : 4
byt e s p e r s e c t o r : 5 1 2
_ dos_geti rive 204

Daer/pt/an Gets the current disk drive using system call INT Ox19.

#include <dos.h>

void _dos_getdrive( unsigned *drive );

drive Current-drive return buffer

Remarks The _dos_getdrive routine uses system call Ox 19 to obtain the current disk drive. The cur­
rent drive is returned in the word that drive points to: 1 = drive A, 2 = drive B, and so on.

Return Value None.

Campatlblllty D ANSI • DOS D OS/2 D U N IX D XEN IX

See Also _dos_getdiskfree, _dos_setdrive, _getdrive

I * D G D R I V E . C : T h i s p r o g r a m p r i n t s t h e l et t e r of t h e c u r r e n t d r i v e ,
* c h a n g e s t e d e fa u l t d r i v e t o A , t h e n r et u r n s t h e n umbe r o f d i s k d r i v e s .
*I


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


v o i d ma i n ( )
(
u n s i gned l dd r i v e , newd r i ve ;
u n s i gned numb e r_of_d r i v e s ;

J
I * P r i nt u r rent d e f a � l t d r i v e i n f o rma t i on * /
_d o s_g e t d � i v e ( & o l d d r i v e l ;
p r i n t f { · � h e c u r re n t d r i ve i s : % c \ n " , ' A ' + o l d d r i v e -

1 );
I
I * Set d e a u l t d r i v e to be d r i v e A * /

j
p r i n t f { " C h a n g i ng d e fa u l t d r i v e t o A \ n " ) ;
_d o s_s etd i v e < 1 , & n umb e r_of_d r i v e s l ;

/ * Get n e d e fa u l t d r i v e i n f o rma t i on a n d t ot a l numb e r of d r i v e s * /


_d o s_g e t d r i v e ( &newd r i v e ) ;
p r i n t f { " T h e c u r re n t d r i v e i s : % c \ n " , ' A ' + n ewd r i v e -
1 l;
p r i n t f ( " N umber of l o g i c a l d r i v e s : %d \ n " , number_of_d r i v e s l ;
205 _ dos_getdrive
/ * Re s t o r e d e fa u l t d r i v e * /
_d o s_s etd r i v e ( o l d d r i v e , & n umb e r_of_d r i v e s ) ;

Output

T h e c u r re n t d r i v e i s : C
C h a n g i n g d e fa u l t d r i v e t o A
The cu rrent d r i ve i s : A
N umbe r of l og i c a l d r i v e s : 2 6
_ das_ge 1eattrf 206

Description Gets the current attributes of a file or directory, using system call INT Ox43.

#include <dos.h>

#include c;::errno.h>

unsigned _dos_getfileattr( char *pathname, unsigned *attrib );

pathname Full path of target file/directory


attrib Word to store attributes in

Remarks The _dos_getflleattr routine uses system call Ox43 to obtain the current attributes of the
file or directory pointed to by pathname . The attributes are copied to the low-order byte of
the attrib word. Attributes are represented by manifest constants, as described below:

Constant Meaning

_A_ARCH Archive. Set whenever the file is changed, or cleared by the


DOS BACKUP command.
_A_mDDEN Hidden file. Cannot be found by a directory search. ·

_A_NORMAL Normal. File can be read or written without restriction.


_A_RDONLY Read-only. File cannot be opened for a write, and a file with
the same name cannot be created.
_A_SUBDIR Subdirectory.
_A_SYSTEM System file. Cannot be found by a directory search.
_A_VOLID Volume ID. Only one file can have this attribute, and it must
be in the root directory.

Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to ENOENT, indicating that the target file or directory could be found.
207 _ dos getfileattr
_

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

See Also access, chmod, _dos_setfileattr, umask

Exampm _________________________________________________________________

I * D G F I L EAT . C : T h i s p r o g r a m c re a t e s a f i l e w i t h t h e s pec i f i ed a t t r i b u t e s ,
* t h en p r i n t s t h i s i n fo rma t i o n b e f o r e c h a n g i ng t h e f i l e a t t r i butes b a c k
* t o n o rma l .
*/

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

v o i d ma i n ( )
(
u n s i gned o l d a t t r i b , n ewa t t r i b ;
i n t fh ;

I * Get a nd d i s p l ay f i l e a t t r i b u t e * /
_d os_getfi l ea t t r C " DG F I LEAT . C " , &ol d a tt r i b ) ;
p r i n t f ( " At t r i b u t e : 0x% . 4x \ n " , o l d a t t r i b ) ;
i f ( ( o l d a t t r i b & _A_RDON LY ) ! = 0 )
p r i n t f ( " Re a d on l y f i l e \ n " ) ;
el se
pri ntf ( " Not a r e a d onl y fi l e . \ n " ) ;

/ * Re s e t f i l e a t t r i b u t e t o n o rma l f i l e * /
_d o s_s e t f i l ea t t r ( " DG F I L EAT . C " , _A_RDON LY ) ;
_d o s_g et f i l e a t t r C " DG F I L EAT . C " , &newa tt r i b ) ;
p r i n t f C " A t t r i b u t e : 0x% . 4x \ n " , n ewa tt r i b ) ;

/ * Res t o r e fi l e a t t r i b u t e * /
_d o s_s e t f i l ea t t r ( " DG F I LEAT . C " , o l d a t t r i b ) ;
_d o s_g et f i l e a t t r ( " DG F I L EAT . C " , & n ewatt r i b ) ;
p r i n t f ( " A t t r i b u t e : 0x% . 4x \ n " , n ewa t t r i b ) ;

Output

Att r i b u t e : 0x0020
Not a read onl y fi l e .
Att r i b u t e : 0x000 1
Att r i b u t e : 0x0020
208

Description Gets the date and time a file was last written, using system call INT Ox57.

#include <dos.h>

#include <errno.h>

unsigned _dos_getftime( int handle, unsigned *date, unsigned *time );

handle Target file


date Date-return buffer
time Time-return buffer

Remarks The _dos_getftime routine uses system call Ox57 to get the date and time that the specified
file was last written. The file must have been opened with a call to _dos_open or
_dos_creat prior to calling _dos_getftime. The date and time are returned in the words
pointed to by date and time. The values appear in the DOS date and time format:

Time Bits Meaning

0-4 Number of 2-second increments (0-29)


5 -10 Minutes (0-59)
1 1-1 5 Hours (0-23)

Date Bits Meaning

0- 4 Day ( 1-3 1 )
5- 8 Month (1-12)
9-15 Year (1980-2099)

Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating that an invalid file handle was passed.
209 _ dos getftime
_

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

See Also _dos_setftime, fstat, stat

I * D G FT I M E . C : T h i s p r o g r a m d i s p l ays a nd mod i f i e s t h e d a t e a nd t i me
* f i e l d s of a f i l e .
*/

#i n c l ude <fcntl . h>


#i n c l u d e <stdi o . h>
#i n c l u d e <stdl i b . h>
Ii i n c l u d e <dos . h>

v o i d ma i n ( )
{
I * FEDC BA98 7 6 54 3 2 1 0 */
u n s i gned n ew_d a t e = 0 x l 84 f ; I * 000 1 1000 0 1 00 1 1 1 1 2/ 15/92 */
u n s i g n ed n ew_t i me = 0x48e0 ; I * 0 1 00 1000 1 1 1 0 0000 9 : 07 AM */
u n s i gned o l d_d a t e , o l d_t i me ;

i n t fh ;

I * Open f i l e w i t h _d os_open funct i o n * /


i f ( _d os_open C " d g ft i me . obj " , O_RDO N LY , & f h ) ! = 0 )
exi t ( 1 ) ;

I * Get f i l e d a t e a n d t i me * /
_d o s_g et ft i me ( f h , & o l d_d a t e , &ol d_t i me ) ;
p r i n t f ( " O l d d a t e f i e l d : 0x% . 4x \ n " , o l d_d a t e ) ;
p r i n t f ( " O l d t i me f i e l d : 0x% . 4x \ n " , o l d_t i me ) ;
s y s t e m ( " d i r d g f t i me . ob j " ) ;

I * Mod i fy f i l e d a t e a n d t i me * /
i f ( ! _dos_s et ft i me ( f h , new_d a t e , n ew_t i me > >
{
_d os_g e t ft i me ( f h , &n ew_d a t e , &new_t i me ) ;
p r i n t f ( " N ew d a t e f i e l d : 0x% . 4x \ n " , new_d a t e ) ;
p r i n t f ( " N ew t i me f i e l d : 0x% . 4x \ n " , n ew_t i me > :
s y s t e m ( " d i r d g ft i me . ob j " > :

I * R e s t o r e d a t e a n d t i me * /
_d os_s et ft i me C f h , o l d_d a t e , o l d_t i me > :
)
_d o s_c l o s e ( fh > :
_ dos g lflime
_ 210

Output

Ol d date f el d : 0x12cf
O l d t i me f e l d : 0x94bb

V o l ume i n d r i v e C i s 052
D i r ec t o ry of C : \ L I B R E F

D G FT I M E 0 J 3923 6 - 1 5 -89 6 : 37 p
1 i l e C s > 1 3 6 7 6 544 by t e s free


N ew date f e l d : 0 x 1 84f
N ew t i me f e l d : 0x48e0

V o l ume i n d r i v e C i s 052
D i r ec t o ry o f C : \ L I B R E F

D G FT I M E 0 J 3923 2- 15-92 9 : 07 a
1 i l e C s ) 1 3 6 7 6 544 by t e s f ree
211 _dos_gettime

DeBt:tlpllon Gets the current system time, using system call INT Ox2C.

#include <dos.h>

void _dos_gettime( struct dostime_t *time );

time Current system time

Remarks The _dos_gettime routine uses system call Ox2C to obtain the current system time. The
time is returned in a dostime_t structure, defined in DOS.H.
The dostime_t structure contains the following elements:

Element Description

unsigned char hour 0 -23


unsigned char minute 0 -59
unsigned char second 0 -59
unsigned char hsecond 1/1 00 second; 0 -99

Relum Value None.

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

See Also _dos_getdate, _dos_setdate, _dos_settime, gmtime, localtime, _strtime

I * D GT I M E . C : T h i s p r o g r a m g e t s a n d d i s p l ays c u r r ent d a t e a n d t i me v a l ues . * /

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

v o i d ma i n ( )
{
s t r u c t d o s d a t e_t d a t e :
s t r u c t d o s t i me_t t i me ;
212

I * Get c u r rent date and t i me v a l ues * /


I
f
_d os_g e td a t e < &d a t e l ;
_d os_g et i me ( &t i me l ;

pri ntf( � Today ' s d a t e i s % d - % d - % d \ n " , d a t e . mon t h , d a t e . d ay , d a t e . y ea r l ;


p r i n t f ( � T h e t i me i s %02d : %0 2 d \ n " , t i me . h o u r , t i me . mi n u t e l ;
!

Output
I
Today ' s d a t e i s 6 - 1 5 - 1 989
The t i me i s l 1 8 : 07
213 _dos_getvect

Out:rlptlan Gets the current value of the interrupt vector, using system call INT Ox35.
#include <dos.II>

void ( _interrupt _far *_dos_getvect( unsigned intnum))( );

intnum Target interrupt vector

Rematlcl The _dos_getvect routine uses system call INT Ox35 to get the current value of the inter­
rupt vector specified by intnum.

This routine is typically used in conjunction with the _dos_setvect function. To replace an
interrupt vector, first save the current vector of the interrupt using _dos_getvect Then set
the vector to your own interrupt routine with _dos_setvect The saved vector can later be
restored, if necessary, using _dos_setvect The user-defined routine may also need the orig­
inal vector in order to call that vector or chain to it with _chain_intr.

Retum Value The function returns a far pointer for the intnum interrupt to the current handler, if there
is one.

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

SN A/sa _chain_intr, _dos_keep, _dos_setvect


214

Description [ Installs TSR (terminate-and-stay-resident) programs in memory, using system call


INT Ox3 1 .

#include <dos.h>

void _dos_keep( unsigned retcode, unsigned memsize );

retcode Exit status code

memsize Allocated resident memory (in 16-byte paragraphs)

Remarks The _dos_keep routine installs TSRs (terminate-and-stay-resident programs) in memory,


using system call INT Ox3 1 .

The routine first exits the calling process, leaving it in memory. It then returns the low­
order byte of retcode to the parent of the calling process. Before returning execution to
the parent process, _dos_keep sets the allocated memory for the now-resident process to
memsize 1 6-byte paragraphs. Any excess memory is returned to the system.
The _dos_keep function calls the same internal routines called by exit. It therefore takes
the following actions:

• Calls ate:xit and one:xit if defined

• Flushes all file buffers.

• Restores interrupt vectors replaced by the C start-up code. The primary one is interrupt
0 (divide by zero). If the emulator math library is used and there is no coprocessor,
interrupts Ox34 through Ox3D are restored. If there is a coprocessor, interrupt 2 is
restored.

The _dos_keep function does not automatically close files; you should do this specifically
unless you want files opened by the TSR installation code to remain open for the TSR.

Do not use the emulator math library in TSRs unless you are familiar with the C start-up
code and the coprocessor. Use the alternate math package (not supplied with Microsoft
QuickC) if the TSR must do floating-point math.
Do not run programs that use _dos_keep from inside the Microsoft Programmer's
WorkBench environment, since doing so causes subsequent memory problems. The
_dos_keep function terminates the program when executed in the Programmer's
WorkBench environment.

Return Value None.


215 _ dos keep
_

Campatlblllly 0 ANSI • DOS 0 OS/2 0 U N IX 0 XENIX

Sn Also _cexit, _chain_intr. _dos_getvect, _dos_setvect, _exit


_dos_ o en 216

Description Opens a file, using system call INT Ox3D.

#include <dos.h>

#include <errno.h>

#include <fcntl.h> Access mode constants


#include <Share.h> Sharing mode constants

unsigned _dos_open( char *filename, unsigned mode, int *handle );

filename Path to an existing file


mode Permissions
handle Pointer to integer

Rematks The _dos_open routine uses system call INT Ox3D to open the existing file pointed to by
filename. The handle for the opened file is copied into the integer pointed to by handle.
The mode argument specifies the file's access, sharing, and inheritance modes by combin­
ing (with the OR operator) manifest constants from the three groups shown below. At
most, one access mode and one sharing mode can be specified at a time.

Constant Mode Meaning

O_RDONLY Access Read-only


O_WRONLY Access Write-only
O_RDWR Access Both read and write
SH_COMPAT Sharing Compatibility
SH_DENYRW Sharing Deny reading and writing
SH_DENYWR Sharing Deny writing
SH_DENYRD Sharing Deny reading
SH_DENYNO Sharing Deny neither
0_NOINHERIT Inheritance by the child File is not inherited
process

Do not use the DOS interface 1/0 routines in conjunction with the console, low-level, or
stream 1/0 routines.
217 _ dos_ open
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following manifest constants:

Constant Meaning

EACCES Access denied (possible reasons include specifying a directory


or volume ID forfilename, or opening a read-only file for
write access)
EINVAL Sharing mode specified when file sharing not installed, or
access-mode value is invalid
EMFILE Too many open file handles
ENOENT Path or file not found

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

See Also _dos_close, _dos_read, _dos_write

I * D O P E N . C : T h i s p r o g r a m u s e s DOS I / O fun c t i o n s t o open a n d c l o s e a f i l e . * /

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


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

v o i d ma i n ( )
(
i nt fh ;

I * Open f i l e w i t h _d o s_open f u n c t i on * /
i f ( _d os_open ( " d a t a l " , O_RDON LY , & f h ) ! = 0 )
p e r ro r C " Open fa i l ed on i n p u t fi l e\ n " ) ;
el se
p r i n t f C " Open s u c c e eded o n i n put fi l e \ n " ) ;

I * C l o s e f i l e wi t h _d os_c l o s e f u n c t i on * /
i f ( _d o s_c l o s e C f h > ! = 0 >
p e r ro r C " C l o s e fa i l ed \ n " ) ;
el se
p r i n t f ( " Fi l e s u c c e s s f u l l y c l o s ed \ n " ) ;
218

I
Output I

b
Open s u c c eect ct o n i np u t f i l e
Fi l e s u c c e s s r u l l y c l o s ed
219 _ dos re d
_ a
Description Reads data from a file, using system call INT Ox3F.

#include <dos.h>

unsigned _dos_read( int handle, void _far *buffer, unsigned count,


unsigned *numread );

handle File to read


buffer Buffer to write to
count Number of bytes to read
numread Number of bytes actually read

Remarks The _dos_read routine uses system call INT Ox3F to read count bytes of data from the file
specified by handle. The routine then copies the data to the buffer pointed to by buffer.
The integer pointed to by numread will show the number of bytes actually read, which
may be less than the number requested in count. If the number of bytes actually read is 0, it
means the routine tried to read at end-of-file.
Do not use the DOS interface 1/0 routines in conjunction with the console, low-level, or
stream 1/0 routines.

Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following constants:

Constant Meaning

EACCES Access denied (handle is not open for read access)


EBADF File handle is invalid

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

See Also _dos_close, _dos_open, _dos_write, read

/**I* ofDREAa D.filC : eThis. program uses the DOS 1 /0 opera ti ons to read the contents
220

#i n c l ude < cntl . h>


#i n c l ude <stdl i b . h>
#i n c l ude <stdi o . h>
#i n c l u d e <dos . h>


v o i d ma i n ( )
! I
i nt fh : I
c h a r b u f e r [ 50 ] ;
u n s i g n e d n umber_rea d ;

!=
/ * Open i l e wi t h _d o s_open f u n c t i on * /
i f ( _d o s�o p e n C " d re a d . c " , O_RDO N LY , &fh ) 0
p e r ro' C " Open fa i l ed on i n put f i l e \ n " > :
el se
pri nt " Open s u c c eeded on i n put f i l e \ n " > :

I * R e a d a t a wi t h _d o s_re a d f u n c t i on * /
_d os_rea C f h , buffe r , 50 , & n umber_re a d > :
p r i n t f C F i r s t 40 c h a r·a c t e r s a re : % . 40 s \ n \ n " , b u f f e r ) :

l
/ * C l o s e f i l e w i t h _d o s_c l o s e f u n ct i on * /
_d os_c l o e C fh > :

Output I
II
O p e n s u c c e e ed on i n put f i l e
F i r s t 40 c h r a c t e r s a re : / * D R EAD . C : T h i s p r o g r a m u s e s t h e D O S
221 _das_setblack

Ducrlpllan Changes the size of a memory segment, using system call INT Ox4A.

#include <dos.h>

unsigned _dos_setblock( unsigned size, unsigned seg, unsigned *maxsize );

size New segment size


seg Target segment

maxsize Maximum-size buffer

Remarks The _dos_setblock routine uses system call INT Ox4A to change the size of seg, pre­
viously allocated by _dos_allocmem, to size paragraphs. If the request cannot be satisfied,
the maximum possible segment size is copied to the buffer pointed to by maxsize.

Return Value The function returns 0 if successful. If the call fails, it returns the DOS error code and
sets ermo to ENOMEM, indicating a bad segment value was passed. A bad segment value
is one that does not correspond to a segment returned from a previous _dos_allocmem
call, or one that contains invalid arena headers.

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

See Also _dos_allocmem, _dos_freemem, realloc functions

I* DALOCMEM . C : T h i s p r o g r a m a l l o c a t e s 20 pa r a g ra p h s of
* t h e a l l o c a t i on t o 40 p a r a g ra p h s , a n d t h e n frees t h e
memo ry , i n c re a s e s

*I
memo ry s p a c e .

#i n c l u d e < d 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 gned s egment ;
u n s i gned ma x s i z e ;
I
_ _ ,
dm; s lblock 222

I
I * Al l o ¢ a t e 2 0 p a r a g ra p h s * /
i f ( _d o , _a l l ocmem ( 20 , &s egment > ! = 0
p r i n f ( " a l l oc a t i on fa i l ed \ n " ) ;
el se
p r i n f ( " a l l oc a t i on s u c c e s s f u l \ n " ) ;

I* I ner a s e a l l oc a t i o n to 40 pa r a g r a p h s * /
i f ( _d o _s etbl oc k ( 40 , s e gme n t , &ma x s i z e ) ! = 0
pri n f ( " a l l o c a t i on i n c r e a s e fa i l ed \ n " ) ;
el s e
pri n f ( " a l l oc a t i on i n c r e a s e s u c c e s s fu l \ n " ) ;

I * Free memory * I
i f ( _d o _f reemem ( s egment ) ! = 0 )
pri n f ( " f ree memo ry fa i l ed \ n " l ;
el se
pri n f C . " f ree memo ry s u c c e s s f u l \ n " ) ;

Output

a l l oc a t i on s u c c e s s f u l
a l l oc a t i o n i n c r ea s e s u c c e s s f u l
free memo r s u c c e s s f u l
223 _ dos
_ setdate
Description Sets the current system date, using system call INT Ox2B.

#include <dos.h>

unsigned _dos_setdate( struct dosdate_t *date );

date New system date

Rematics The _dos_setdate routine uses system call INT


Ox2B to set the current system date. The
date is stored in the dosdate_t structure pointed to by date, defined in DOS.H. The
dosdate_t structure contains the following elements:

Element Description
unsigned char day 1 -3 1
unsigned char month 1 -12
unsigned int year 1980- 2099
unsigned char dayofweek 0 - 6 (0 = Sunday)

Return Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets errno to
EINVAL, indicating an invalid date was specified.

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

See Also _dos_gettime, _dos_setdate, _dos_settime, gmtime, localtime, mktime, _strdate,


_strtime, time

*
I * D ST I M E . C : T h i s p r o g r a m c h a n g e s t h e t i me a n d d a t e v a l ues a n d d i s p l a y s t h e
n e w d a t e a n d t i me v a l u e s .
*I

/Ii n c 1 ude <dos . h>


#i n c l ude <coni o . h>
#i n c l ude < s td i o . h >
#i n c l ude < t i me . h >

I

_ das se a te
_ 224

v o i d ma i n ( ) I
1 �
s t ruct d s d a t e_t o l d d a t e , n ewd a t e = 4 }
3 }
• { 7 }
( 45 }
• ( 1 984 } } :
{ 30 } { 0 } }:

J�
s t ru c t d s t i me_t o l d t i me , n ewt i me = • • •

cha r d a t eb u f [ 40 ] , t i mebu f [ 40 J :

I * Get c r r e n t d a t e a n d t i me v a l u e s * /
_d os_g e t dja t e C &ol d d a t e ) :

•1

_d os_g e t t me C & o l d t i me > :
p r i nt f ( s % s \ n " , _st rd a t e ( d a tebuf ) , _s t rt i me C t i meb uf ) > :

l
I * Mod i fy d a t e a nd t i me s t r u c t u res * /
_d os_s etd t e C &newd a t e > :
_d o s_s e t t " me C &n ewt i me > :
pri ntfC •s % s \ n " , _s t rd a t e C d a tebuf ) , _s t rt i me C t i meb u f ) > :
'
I * Re s t o r o l d d a t e a nd t i me * /
_d o s_s etd t e e &ol d d a t e > :
_d os_s e t t " me C &ol d t i me > :

Output [
0 6 / 1 5 / 89
0 7 / 04 / 84
&1 8 : 2 6 : 09
3 : 4 5 : 30

I
225 _dos_setdrive

Description Sets the default drive, using system call INT OxOE.

#include <dos.h>

void _dos_setdrive( unsigned drive, unsigned *numdrives );

drive New default drive

numdrives Total drives available

Remarks The _dos_setdrive routine uses system call INT OxOE to set the current default drive to the
drive argument: 1 = drive A, 2 = drive B, and so on. The numdrives argument indicates the
total number of drives in the system. If this value is 4, for example, it does not mean the
drives are
designated A, B, C, and D; it means only that four drives are
in the system.

Return Value There is no return value. If an invalid drive number is passed, the function fails without in­
dication. Use the _dos_getdrive routine to verify whether the desired drive has been set.

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

See Also _dos_getdiskfree, _dos_getdrive

I * D G D R I V E . C : T h i s p r o g r a m p r i n t s t h e l et t e r of t h e c u r r e n t d ri v e ,
* c h a n g e s t h e d e fa u l t d r i ve to A , t h e n r e t u r n s t h e number of d i s k d r i v e s .
*I

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


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

v o i d ma i n ( )
{
u n s i gned o l d d r i ve , newd r i ve ;
u n s i gned n umbe r_of_d r i v e s ;

I * P r i n t c u r r ent d e fa u l t d r i ve i n f o rma t i on * /
_d o s_g et d r i v e C &ol d d r i v e ) ;
p r i ntf ( " T h e c u r rent d r i ve i s : % c \ n " , ' A ' + o l d d r i ve - 1 );

I * Set d e fa u l t d r i v e t o be d r i v e A * /
p r i n t f ( " C h a n g i ng d e fa u l t d r i v e t o A \ n " ) ;
_d o s_s etd r i v e C 1 , & n umb er_o f_d r i ves ) ;
I
_dos_+rive 226

� ew defa u l t
i
I * Get d r i v e i n fo rma t i on a n d t o t a l n umbe r of d r i v e s */
_d os_ge� d r i v e ( &newd r i v e ) ;
p r i n t f ( l • T h e c u rrent d r i v e i s : %c \ n " , ' A ' + newd r i v e - 1 );
p r i n t f ( ! " N umbe r of l og i c a l d r i v e s : % d \ n " , n umbe r_of_d r i v e s ) ;

/ * R e s t d r e d e f a u l t d r i ve * /
,
_do s_s e d r i v e < o l d d r i v e , &n umbe r_of_d r i v e s ) ;


Output

T h e c u r ren ' d r i v e i s : C
Changi ng d faul t dri ve to A
T h e c u r rent d r i v e i s : A
N umber of l p g i c a l d r i v e s : 26
227 _dos_setfi/eattr

Description Sets the attributes of the file or directory, using system call INT Ox43.

#include <dos.h>

unsigned _dos_setfileattr( char *pathname, unsigned attrib );

pathname Full path of target file/directory

attrib New attributes

Remarks The _dos_setfileattr routine uses system call INT Ox43 to set the attributes of the file or
directory pointed to by pathname. The actual attributes are contained in the low-order byte
of the attrib word. Attributes are represented by manifest constants, as described below:

Constant Meaning
_A A C
_ R H Archive. Set whenever the file is changed, or cleared by the
DOS BACKUP command.

_A HIDDEN
_ Hidden file. Cannot be found by a directory search.

_A NORMAL
_ Normal. File can be read or written to without restriction.

_A RD ONLY
_ Read-only. File cannot be opened for writing, and a file with
the same name cannot be created.

_ U DIR
A S B
_ Subdirectory.

_A SYSTEM
_ System file. Cannot be found by a directory search.

_A VOLID
_ Volume ID. Only one file can have this attribute, and it must
be in the root directory.

Return Value The function returns 0 if successful. Otherwise, it returns the DOS error code and sets
errno to one of the following:

Constant Meaning
EACCES Access denied; cannot change the volume ID or the
subdirectory.
ENOENT No file or directory matching the target was found.
I
_dos_ + leattr 228

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

See Also _dos_getfileattr

Example �-+-����

�� � �����
I * D G F I L EA � . C : Th i s p r o g r a m c re a t e s a f i l e w i t h t h e s pec i f i ed a t t r i butes ,
: e s t h i s i n f o rma t i o n before c h a ng i n g t h e f i l e a tt r i b u t e s b a c k
0
*/
I
I

l
#i n c l ude < �t d i o . h >
#i n c l ude <d o s . h >
'
v o i d ma i n ( >
(
'

u n s i g n e d o l d a t t r i b , n ewa t t r i b ;
i nt fh ;

I * Get a n d d i s p l a y f i l e a t t r i b u t e * /
_d os_g et � i l e a t t r < " DG F I LEAT . C " , & o l d a t t r i b > ;
p r i n t f ( [ Att r i b u t e : 0x% . 4x \ n " , o l d a t t r i b ) ;
i f ( ( o l r. a t t r i b & _A_RDON LY ) ! = 0 )

el s e

p r i n t ( " Re a d on l y fi l e \ n " ) ;

f
p r i n t ( " N ot a r e a d on l y f i l e . \ n " ) ;

I * Reset I f i l e a t t r i b u t e t o n o rma 1 fi l e * I
_d o s_s et i l e a t t r ( " DG F I LEAT . C " , _A_RDON LY ) ;

l
_d o s_g et i l e a t t r < " DG F I LEAT . C " , & n ewa t t r i b ) ;
p r i n t f ( ' A t t r i b u t e : 0x% . 4x \ n " , n ewa t t r i b l ;

I * Res t o e f i l e a t t r i bute * /
_d os_s et i l e a t t r ( " DG F I LEAT . C " , o l d a t t r i b l ;
_d o s_get i l e a t t r ( " DG F I L EAT . C " , & n ewa t t r i b ) ;
pri ntf( Att ri b u t e : 0x% . 4x \n " , n ew a t t r i b l ;
l
!
Output

l
;
Att r i b u t e : x0020

A t t r i b u t e : � x000 1
Not a read n l y fi l e .

Att r i bute : x0020 f


229 _dos_setltime

Description Sets the date and time for a file, using system call INT Ox57.

#include <dos.h>

unsigned _dos_setftime( int handle, unsigned date, unsigned time );

handle Target file


date Date of last write

time Time of last write

Remarks The _dos_setftime routine uses system call INT Ox57 to set the date and time at which the
file identified by handle was last written to. These values appear in the DOS date and time
fonnat, described in the following lists:

Time Bits Meaning


0-4 Number of two-second increments (0 -29)

5- 10 Minutes (0 -59)
1 1-15 Hours (0 -23)

Date Bits Meaning


0-4 Day ( 1-3 1 )

5 -8 Month (1-12)

9-15 Year since 1980 (for example, 1989 is stored as 9)

Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating that an invalid file handle was passed.
_dos_se!ltime 230

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

See Also _dos_getftime, fstat, stat

Exampm __ -+��������������������������������

I * D G FT I M E . d : T h i s p r o g r a m d i s p l a y s a n d mod i f i e s t h e d a t e a nd t i me

!
ff
* f i el d s o a f i l e .
*/

{fi n c l ude
{fi n c l ude
q
<f ntl . h>
< s tjd i o . h>
{fi n c l ude < s tj d l i b . h >
#i n c l ude tj
<d s . h >
I
v o i d ma i n ( )
[
I * FEDC BA98 7 6 54 3 2 1 0 */
u n s i g n e d 1n ew_d a t e 0x 1 84f ; = I * 000 1 1 000 0 1 00 1 1 1 1 2/ 15/92 */
I * 0 1 00 1 000 1 1 1 0 0000 9 : 0 7 AM * /
p
u n s i g n ed r ew_t i me - 0x48e0 ;
u n s i gned l d_d a t e , o l d_t i me ;

I
i nt fh :


I * Open f l e wi t h _d os_open f u n c t i o n * /
i f ( _d os_ p pen ( " d g ft i me . obj " , O_RDO N LY , &fh ) ! = 0 )
exi t ( � > :
!

·�,
I * Get f i e d a t e a n d t i me * /
_d os_getft i me ( fh , &ol d_d a t e , &ol d_t i me ) ;
pri ntf( l d d a t e fi e l d : 0x% . 4x \ n " , o l d_d a t e ) ;

,
p r i n t f ( • l d t i me fi e l d : 0x% . 4 x \ n " , o l d_t i me ) ;
s y s t e m ( " i r dgft i me . obj " ) ;
I
\
I * Mod i fy fi l e d a t e a nd t i me * /
i f ( ! _d o s Ts e t ft i me ( fh , new_d a t e , new_t i me ) )
[
_d os_g + t ft i me ( fh , &n ew_d a t e , &n ew_t i me ) ;
p r i n t f ( " N ew d a t e fi e l d : 0x% . 4x \ n " , n ew_d a t e > ;

p r i n t f " N ew t i me f i e l d : 0x% . 4x \ n " , n ew_t i me > :
sy s t em , " d i r d g f t i me . obj " ) ;

t�
I * Res o r e d a t e a n d t i me * /
_d o s_s t ft i me ( f h , o l d_d a t e , o l d_t i me l ;
i
_d o s_c l o s C f h ) ; ,I
I
231 _dos_setflime

Output
Ol d date fi el d : 0x12cf
O l d t i me f i e l d : 0x94bb

V o l ume i n d r i v e C i s OS2
D i rectory of C : \ L I B R E F

D G FT I M E OBJ 3923 6 - 1 5-89 6 : 37p


1 F i l e C s > 1 3 6 7 6 544 byt e s f ree

New date f i e l d : 0x 184f


N ew t i me f i e l d : 0x48e0

V o l ume i n d r i v e C i s OS2
D i rectory o f C : \ L I B R E F

DGFT I M E OBJ 3923 2 - 1 5-92 9 : 07 a


1 F i l e C s > 1 3 6 7 6 544 byt e s f ree
232

DIBl:l'/pl/an
\ Sets the current system time, using system call INT Ox2D.

#include <dos.h>

unsigned _dos_settime( struct dostime_t *time );

time New system time

R1matlt1 The _dos_settime routine uses system call INT Ox2D to set the current system time to the
value stored in the dostime_t structure that time points to, as defined in DOS.H. The
dostime_t structure contains the following elements:

Element Description
unsigned char hour 0 -23
unsigned char minute 0 -59
unsigned char second 0 -59
unsigned char hsecond Hundredths of a second; 0 -99

RBlurn Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets ermo to
EINVAL, indicating an invalid time was specified.

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

S11 A/sa _dos_getdate, _dos_gettime, _dos_setdate, gmtime, localtime, mktime,


_strdate, _strtime

Exampm �--+����---
I
1 * D ST I M E . c : T h i s p ro g r a m c h a n g e s t h e ti me a n d d a t e v a l ues a n d d i s p l a y s t h e
* n ew d a t e a nd t i me v a l u e s .
*/

/Ji n c 1 ude
#i n c l ude
#i n c l ude

< d o1 s . h >
< c i o . h>
< s t i o . h>
#i n c l ude <ti e . h>
233 _dos_ settime

v o i d ma i n ( )
(
s t r u c t d o s d a t e_t ol d d a t e , n ewd a t e 4 l , ( 7 l , ( 1 984 l l ;
3 l , ( 45 l , ( 30 l , ( 0 l l ;
=
s t r u c t d o s t i me_t o l d t i me , n ewt i me =

cha r d a t e b u f [ 40 J , t i meb u f [ 40 J ;

I * Get c u r r e n t d a t e a n d t i me v a l ues * /
_d o s_get d a t e ( & o l d d a t e ) ;
_d o s_g et t i me ( & o l d t i me ) ;
pri ntf( "%s % s \ n " , _s t rd a t e ( d a t e b u f ) , _s t rt i me ( t i mebuf ) ) ;

I * M o d i fy d a t e a nd t i me s t r u c t u res * /
_d o s_s e td a t e ( &newd a t e ) ;
_d o s_s e t t i me ( &newt i me ) ;
p r i n t f ( " %s % s \ n " , _s t rd a t e ( d a tebuf ) , _s t rt i me ( t i mebuf ) ) ;

I * R e s t o r e o l d d a t e a nd t i me * /
_d o s_s e t d a t e ( & o l d d a t e ) ;
_d os_sett i m� ( &ol d t i me ) ;

Output

06/ 15/89 1 8 : 2 6 : 09
0 7 / 04 / 84 03 : 4 5 : 30
234

Description Sets the current value of the interrupt vector, using system call INT Ox25.

#include <dos.h>

void _dos_setvect( unsigned intnum, void( _interrupt _far *handler)());

inmum Target-interrupt vector

handler Interrupt handler for which to assign intnum

rupt vector intnum to the function pointed to by handler. Subsequently, whenever the
Remarks The dos setvect routine uses system call INT Ox25 to set the current value of the inter­

intnum interrupt is generated, the handler routine will be called. If handler is a C function,
it must have been previously declared with the interrupt attribute. Otherwise, you must
make sure that the function satisfies the requirements for an interrupt-handling routine. For
example, if handler is an assembler function, it must be a far routine that returns with an
IRET instead of a RET.

The interrupt attribute indicates that the function is an interrupt handler. The compiler
generates appropriate entry and exit sequences for the interrupt-handling function, includ­
ing saving and restoring all registers and executing an IRET instruction to return.

The _dos_setvect routine is generally used with the _dos_getvect function. To replace an
interrupt vector, first save the current vector of the interrupt using _dos_getvect. Then set
the vector to your own interrupt routine with _dos_setvect. The saved vector can later be
restored, if necessary, using _dos_setvect. The user-defined routine may also need the orig­
inal vector in order to call it or to chain to it with _chain_intr.

Registers and Interrupt Functions

When you call an interrupt function, the DS register is initialized to the C data segment.
This allows you to access global variables from within an interrupt function.

In addition, all registers except SS are saved on the stack. You can access these registers
within the function if you declare a function parameter list containing a formal parameter
for each saved register. The following example illustrates such a declaration:
2as dos_setvect

v o i d _i n t e r rupt _fa r i n t_h a n d l e r ( u n s i gned _e s , u n s i g n e d _d s ,


u n s i g n ed _d i , u n s i gned _s i ,
u n s i gned _bp , u n s i gned _s p ,
u n s i gned _bx , u n s i gned _dx ,
uns i g n ed _ex , u n s i g n e d _a x ,
uns i gned _i p , u n s i g n ed _c s ,
u n s i gned _fl a g s )

The formal parameters must appear in the opposite order from which they are pushed onto
the stack. You can omit parameters from the end of the list in a declaration, but not from
the beginning. For example, if your handler needs to use only DI and SI, you must still
provide ES and OS, but not necessarily BX or DX.

You can pass additional arguments if your interrupt handler will be called directly from C
rather than by an INT instruction. To do this, you must declare all register parameters and
then declare your parameter at the end of the list.

The compiler always saves and restores registers in the same, fixed order. Thus, no matter
what names you use in the formal parameter list, the first parameter in the list refers to ES,
the second refers to DS, and so on. If your interrupt routines will use in-line assembler,
you should distinguish the parameter names so that they will not be the same as the real
register names.

If you change any of the register parameters of an interrupt function while the function is
executing, the corresponding register contains the changed value when the function re­
turns. For example:

v o i d _i n t e r rupt _fa r i n t_h a nd l e r ( u n s i gned _es , u n s i gned _d s ,


uns i gned _d i , u n s i g n e d _s i )

_d i = -1;

This code causes the DI register to contain -1 when the handler function returns. It is not a
good idea to modify the values of the parameters representing the IP and CS registers in in­
terrupt functions. If you must modify a particular flag (such as the carry flag for certain
DOS and BIOS interrupt routines), use the OR operator ( I ) so that other bits in the flag
register are not changed.

When an interrupt function is called by an INT instruction, the interrupt-enable flag is


cleared. If your interrupt function needs to do significant processing, you should use the
_enable function to set the interrupt flag so that interrupts can be handled.
236

Precautions far lntemJpt Functions

Since DOS is not reentrant (a DOS interrupt cannot be called from inside a DOS interrupt),
it is usually not safe to call from inside an interrupt function any standard library function
that calls DOS INT 2 1 H. Similar precautions apply to many BIOS functions. Functions
that rely on INT 2 1 H calls include 1/0 functions and the _dos family of functions. Func­
tions that rely on the machine's BIOS include graphics functions and the _bios family of
functions. It is usually safe to use functions that do not rely on INT 2 1 H or BIOS, such as
string-handling functions. Before using a standard library function in an interrupt function,
be sure that you are familiar with the action of the library function.

Return Value None.

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

See Also _chain_intr, _dos_getvect , _ dos_keep


237 _dos_ write

Descr/pllan Writes a buffer to a file, using system c all INT Ox40.

#include <dos.h>

unsigned _dos_write( int handle, void _far *buffer, unsigned count,


unsigned *numwrt );

handle File to write to


buffer Buffer to write from
count Number of bytes to write
numwrt Number of bytes actually written

Remarks The _dos_write routine uses system call INT Ox40 to write data to the file that handle ref­
erences; count bytes of data from the buffer to which buffer points are written to the file.
The integer pointed to by numwrt will be the number of bytes actually written, which may
be less than the number requested.

Do not use the DOS interface routines with the console, low-level, or stream 1/0 routines.

Retum Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following manifest constants:

Constant Meaning

EACCES Access denied (handle references a file not open for write
access)
EBADF Invalid file handle

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

See Also _dos_close, _dos_open, _dos_read, write

I* DW R I T E . C : T h i s p r o g r a m u s e s DOS I / O f u n c t i o n s t o w r i t e t o a f i l e . * /

# i n c l ude <fcntl . h>


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

0
_das_wri e 2aa

v o i d ma i n ( )

{ l
c h a r o u t buffer [ J = " H e l l o " ;
i nt fh ;
u n s i g n e d n_w r i t t e n ;

1

I * Open i l e wi t h _d o s_c r e a t funct i on * /
f ( _d o s 1 c r e a t ( " d a t a " , _A_N O RMA L , &fh ) == 0 )


_d os_ r i t e ( f h , out =buff e r , 5 , &n_w r i t t e n > :
/ * W r i t e da t a wi t h d o s w r i t e f u n c t i on * /

I
p r i n t n < " N umber of c h a r a c t e r s w r i t t e n : % d \ n " , n_w r i tten > :

_d o s_cp o s e ( f h > :
p r i n t fi( " C onten t s of fi l e a re : \ n " > :
s y s t e ( " type d a t a " ) ;

Output

N umber of c h ra c t e r s w r i t t e n : 5
C o n t e n t s o f i l e a re :
Hel l o
239 dosexterr

Description Gets register values returned by INT Ox59.

#include <dos.h>

int dosexterr( struct DOSERROR *errorinfo );

errorinfo Extended DOS error information

Remarks The dosexterr function obtains the extended error information returned by the DOS sys­
tem call INT Ox59 and stores the values in the structure pointed to by errorinfo. This func­
tion is useful when making system calls under DOS versions 3.0 or later, which offer
extended error handling.
The structure type DOSERROR is defined in DOS.ff. The DOSERROR structure contains
·

the following elements:

Element Description

int exterror AX register contents

char class BH register contents


char action BL register contents
char locus CH register contents

Giving a NULL pointer argument causes dosexterr to return the value in AX without
filling in the structure fields. See MS-DOS Encyclopedia (Duncan, ed.; Redmond, WA:
Microsoft Press, 1 988) or Programmer's PC Sourcebook (Hogan; Redmond, WA:
Microsoft Press, 1988) for more information on the register contents.·

Return Value The dosexterr function returns the value in the AX register (identical to the value in the
exterror structure field).

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

The dosexterr function should be used only under DOS versions 3.0 or later.
dosexte r 240

SBB Also perror

Exampm �+-������-
1 * DOS E X E R . C : T h i s p r o g r a m t r i e s t o open t h e fi l e t e s t . d a t . I f t h e
* a ttempt d open opera t i on fa i l s , t h e p r o g r a m u s e s d o s e x t e r r t o d i s p l ay
* extende e r r o r i n fo rma t i o n .
*I

1
/ti n c l u d e < os . h>
/ti n c l u d e < o . h>
#i n c l u d e < cntl . h>
#i n c l ude < tdi o . h>

v o i d ma i n (
{ I
s t r u c t � O S E RRO R d o s e r r o r ;
i nt fd ; I
I
1
I * Atte � pt to open a n o n - ex i s t e n t fi l e * /
1
,
f ( C fd = open ( " N O S U C H F . I L E " , O_RDO N LY l l � -1

dose terrC &doserror l ;


p r i n f C " E r ro r : %d C l a s s : %d Ac t i on : %d L o c u s : % d \ n " ,
d o s e r ro r . e x t e r r o r , d o s e r r o r . c l a s s ,
d o s e r r o r . a c t i on , d o s e r ro r . l o c u s l ;

el s e
{
p r i n f ( " Open s u c c eeded s o n o extended i n forma t i on p r i n t ed \ n " l ;
c l o s ( fd l ;

Output I

E r ro r : 2 � l ass : 8 Ac t i o n : 3 Locus : 2

I
I
241 dup, dup2

Description Create a second handle for an open file (dup), or reassign a file handle (dup2).

#include <io.h Required only for function declarations

int dup( int handle );


int dup2( int hand/el , int handle2 );

handle, hand/el Handle referring to open file


handle2 Any handle value

Remadts The dup and dup2 functions cause a second file handle to be associated with a currently
open tile. Operations on the file can be carried out using either file handle. The type of
access allowed for the file is unaffected by the creation of a new handle.
The dup function returns the next available file handle for the given file. The dup2 func­
tion forces handle2 to refer to the same file as hand/el . If handle2 is associated with an
open file at the time of the call, that file is closed.

Retum Value The dup function returns a new file handle. The dup2 function returns 0 to indicate
success. Both functions return -1 if an error occurs and set ermo to one of the following
values:

Value Meaning
EBADF Invalid file handle
EMFILE No more file handles available (too many open files)

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

SBB A/so close, creat, open

I* D U P . C : T h i s p r o g r a m u s e s t h e v a r i a b l e o l d t o s a v e t h e o r i g i n a l
* I t t h en o p e n s a n ew f i l e named n ew a nd f o r c e s s t d o u t to refer
stdout .

* t o i t . Fi n a l l y , i t r e s t o res s t d out t o i t s o r i g i n a l s t a t e .
*I
//i n c l u d e < i o . h >
#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 >
242

v o i d ma i n < > •
!
i n t o l d ; I;
FI LE *ne · ; l
ol d = du ( 1 l ; / * " o l d " n ow refe rs t o " s t d o u t " * /
I * Note : fi l e h a n d l e 1 � " s tdout " * /
i f ( ol d += -1 >

f
(
'

I
p e r r o ( " d up ( 1 > fa i l u re " l ;
exi t ( l l l ;

w r i t e ( o l d , " T h i s goes to s t d o u t f i r s t \ r \ n " , 27 ) ;


i f ( ( n eW fopen ( " d a ta " , " w " ) ) == N U L L
=

(
p ut s ( " C a n ' t open f i l e ' d a t a ' \ n " ) ;
exi t ( 1 l ;

{
I * s t d o u n ow refe r s t o fi l e " d a t a " * /
i f ( - 1 =t d u p 2 ( f i l eno ( new ) , 1 ) )
(
1
I
p e r r o r. ( " C a n ' t d u p 2 s t d o u t " > :
ex i t ( 1 ) ;
I
puts ( "T�i s goes to fi l e ' data ' \ r\ n " ) ;
i
/ * Fl u s h i s t d o u t s t r e a m buffer s o i t goes t o c o r rect f i l e * /
ffl u s h ( � t d o u t > :
fc l o s e < � ew l ;

I * Resto�e ori g i na l stdout */


d up2 < o l � , 1 l ;
p u t s ( " T � i s goes to s t d o ut \ n " l ;
puts ( " T�e fi l e ' da t a ' conta i ns : " ) ;
i
s y s t em ( ty pe d a t a " ) ;

:!
Output

Thi s goes s tdout f i r s t


Thi s goes s td o u t
i
I

T h i s goes to fi l e ' da t a '


The fi l e ' data ' conta i n s :
i

I
243 ecvt
Description Converts a double number to a string.

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

char *ecvt( double value, int count, int *dee, int *sign );

value Number to be converted


count Number of digits stored
dee Stored decimal-point position
sign Sign of converted number

Remarks The ecvt function converts a floating-point number to a character string. The value argu­
ment is the floating-point number to be converted. The ecvt function stores up to count
digits of value as a string and appends a null character ('\0'). If the number of digits in
value exceeds count, the low-order digit is rounded. If there are fewer than count digits,
the string is padded with zeros.

Only digits are stored iQ the string. The position of the decimal point and the sign of value
can be obtained from dee and sign after the call. The dee argument points to an integer
value giving the position of the decimal point with respect to the beginning of the string. A
0 or negative integer value indicates that the decimal point lies to the left of the first digit.
The sign argument points to an integer indicating the sign of the converted number. If the
integer value is 0, the number is positive. Otherwise, the number is negative.
The ecvt and fcvt functions use a single statically allocated buffer for the conversion. Each
call to one of these routines destroys the result of the previous call.

Return Value The ecvt function returns a pointer to the string of digits. There is no error return.

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

See A/Ba atof, atoi, atol, fcvt, gcvt

I* E C VT . C : T h i s p ro g r a m u s e s e c v t
* n umber t o a c h a ra c t e r s t r i ng .
t o c o n v e rt a fl oa t i n g - p o i nt

*I
#i n c l ude < s t d l i b . h >
#i n c l ude < s t d i o . h >
ecvt 2u

l
v o i d ma i n ( )
(
i nt ec i ma l , s i g n ;
char b u f fe r :

j
i
i nt r ec i s i on = l fil ;
doubl e ource = 3 . 141 5926535 ;

b u f f e r = e c v t C s o u rce , p r e c i s i o n , &dec i ma l , &s i g n > :


p r i n t f C s o u rce : %2 . 1 0 f buffe r : ' % s ' d e c i ma l : %d s i gn : %d\n " ,
o u r c e , b u f fe r , d ec i ma l , s i gn > :

I
,
Output

s o u r c e : 3 . 1 1 59 2 6 5 3 5 b u f fe r : ' 3 14 1 5 9 2 6 54 ' d ec i ma l : 1 s i gn : fil


245 _ellipse Functions

DBBcriptlon Draw ellipses.

#include <graph.h>

short _far _ellipse( short control, short xl, short yJ, short x2, short y2 );
short _far _ellipse_w( short control, double wxl, double wyl, double wx2,
double wy2 ) ;
short _far _ellipse_wxy( short control, struct _wxycoord _far *pwxyl,
struct _wxycoord _far *pwxy2 );

control Fill flag


xl , yl Upper-left corner of bounding rectangle

x2, y2 Lower-right corner of bounding rectangle


wxl , wyl Upper-left corner of bounding rectangle
wx2, wy2 Lower-right comer of bounding rectangle
pwxyl Upper-left corner of bounding rectangle
pwxy2 Lower-right comer of bounding rectangle

Remarks The _ellipse functions draw ellipses or circles. The borders are drawn in the current color.
In the _ellipse function, the center of the ellipse is the center of the bounding rectangle de­
fined by the view-coordinate points (xl , yl) and (x2, y2).

In the _ellipse_w function, the center of the ellipse is the center of the bounding rectangle
defined by the window-coordinate points (wxl, wyl) and (wx2, wy2).

In the _ellipse_wxy function, the center of the ellipse is the center of the bounding rec­
tangle defined by the window-coordinate pairs (pwxyl) and (pwxy2).

If the bounding-rectangle arguments define a point or a vertical or horizontal line, no fig­


ure is drawn.
The control argument can be one of the following manifest constants:

Constant Action
_GFILLINTERIOR Fills the ellipse using the current fill mask
_GBORDER Does not fill the ellipse
I
I

_ellipse Functions 246

The control option given by _GFILLINTERIOR is equivalent to a subsequent call to the


_floodtill function, using the center of the ellipse as the starting point and the current color
(set by _setcolor) as the boundary color.

Relum Value The _ellipse functions return a nonzero value if the ellipse is drawn successfully; other­
wise, they return 0.

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

See A/sa · _arc functions, _floodml, _grstatus, _lineto functions, _pie functions,
_polygon functions, _rectangle functions, _setcolor, _settillmask

Exam�• ---+---

1* ELLI PSE . : T h i s p r o g r a m d raws a s i mp l e e l l i ps e . * /

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


#i n c l ude < s d l i b . h >
#i n c l ude < g a p h . h >

v o i d ma i n ( )
{
I* Fi nd l
v a l i d g r a p h i c s mod e . * I

\
i f ( ! _s e v i d eomod e C _MA X RESMOOE )
ex i t ( 1 ) ;

_e l l i ps e _G F I L L I NT E R I O R , 80 , 50 , 240 , 1 50 ) ;

r
/ * S t r i k a ny key to c l ea r s c reen . * /
getc h C ) ;
_s e t v i d e mod e ( _O E FAU LTMO O E ) ;
247 _enable

D•crlpllon Enables interrupts.

#include <dos.h>

void _enable( void );

Rsmatks The _enable routine enables interrupts by executing an 8086 STI machine instruction.

Rstum Va/us None.

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

See Also _disable


I
I
_endthr ad , 241

OBBt:rlpt/an Tenninates an OS/2 thread.

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

void _far _endthread( void );

Dat:rlptlan The _endthread function tenninates a thread created by _beginthread.


Because threads tenninate automatically, the _endthread function is nonnally not re­
quired. It is used to tenninate a thread conditionally.

The OS/2 function DosE:xit should not be used to tenninate threads created by the
_beginthread function. If DosE:xit is used, the results are unpredictable.

Return Va/us None.

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

S11 A/1a _beginthread

Examp/1 See the example for _beginthread.


249 eat

Description Tests for end-of-file.

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

int eof( int handle );

handle Handle referring to open file

Remades The eof function determines whether the end of the file associated with handle has been
reached.

Retum Value The eof function returns the value 1 if the current position is end-of-file, or 0 if it is not. A
return v alue of -1 indicates an error; in this case, errno is set to EBADF, indicating an
invalid file handle.

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

See Also clearerr, feof, ferror, perror

/ * E O F . C : T h i s p r o g r a m r e a d s d a t a from a f i l e ten by t e s a t a t i me
* u n t i l t h e e n d of t h e f i l e i s rea c h ed o r a n e r r o r i s e n c o u n t e red .
*I

I/i n c l ude < i o . h>


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

v o i d ma i n ( )
{
i n t f h , c o u n t , t ota l = 0 ;
c h a r b u f [ 10 ] ;

i f ( C f h = open ( " eo f . c " , O_RDO N LY ) ) == - 1 )


exi t ( 1 ) ;
eat 250

I * Cyc l e n t i l end o f f i l e rea c h ed : */


w h i l e ( ! e f( f h ) l
{
/ * Att mpt to r e a d i n 10 bytes : */
i f ( C c unt r ea d ( f h , buf , 1 0 > > -1
{
� �

t
p e r o r ( " Re a d e r r o r • ) ;
bre k ;

I* Tot up a c t u a l bytes r e a d * /
tot a 1 count ;

�r i n t f ( • umb e r o f byt e s r e a d = % d \ n " , tota l ) :


cl ose ( fh > :

Output

Number of by e s rea d = 715


251 exec Functions

Description Load and execute new child processes.

#include <proces,,.h> Required only for function declarations

int execl( char *cmdname, char *argO, ... char *argn, NULL );
int execle( char *cmdname, char *argO, ... char *argn, NULL, char **envp ) ;
int execlp( char *cmdname, char *argO, . char *argn, NULL );
..

int execlpe( char *cmdname, char *argO, . . char *argn, NULL, char **envp );
.

int execv( char *cmdname, char **argv );


int execve( char *cmdname, char **argv, char **envp ) ;
int execvp( char *cmdname, char **argv ) ;
int execvpe( char *cmdname, char **argv, char **envp );

cmdname Path name of file to be executed


argO, ... argn List of pointers to arguments
argv Array of pointers to arguments
envp Array of pointers to environment settings

Remarks The exec functions load and execute new child processes. When the call is successful in
DOS, the child process is placed in the memory previously occupied by the calling
process. Under OS/2, calling an exec function is equivalent to calling the corresponding
function with the P_NOWAITO argument specified, followed by a call to the exit function.
Sufficient memory must be available for loading and executing the child process.
All of the exec functions use the same operating system function. The letter(s) at the end
of the function name determine the specific variation, as shown in the following list:

Letter Variation
e An array of pointers to environment arguments is explicitly
passed to the child process.
Command-line arguments are passed individually to the exec
function.
p Uses the PATH environment variable to find the file to be
executed
v Command-line arguments are passed to the exec function as
an array of pointers.
252

I The cmdname argument specifies the file to be executed as the child process. It can specify

II
a full path (from the root), a partial path (from the current working directory), or just a file
name. If cmdname does not have a file-name extension or does not end with a period (.),
1 the exec function searches for the named file; if the search is unsuccessful, it tries the same
base name, first with the extension .COM, then with the extension .EXE. If cmdname has
an extension, only that extension is used in the search. If cmdname ends with a period, the
exec calls search for cmdname with no extension. The execlp, execlpe, execvp, and
execvpe routines search for cmdname (using the same procedures) in the directories
specified by the PATH environment variable.
If cmdname contains a drive specifier or any slashes (i.e., if it is a relative path name), the
exec call searches only for the specified file and no path searching is done.
Arguments are passed to the new process by giving one or more pointers to character
strings as arguments in the exec call. These character strings form the argument list for the
child process. The combined length of the strings forming the argument list for the new
process must not exceed 1 28 bytes (in real mode only). The terminating null character
('\0') for each string is not included in the count, but space characters (inserted automat­
ically to separate the arguments) are counted.
The argument pointers can be passed as separate arguments (execl, execle, execlp, and
execlpe) or as an array of pointers (execv, execve, execvp, and execvpe). At least one ar­
gument, argO, must be passed to the child process; this argument is argv[O] of the child
process. Usually, this atgument is a copy of the cmdname argument. (A different value
will not produce an error.) Under versions of DOS earlier than 3.0, the passed value of
argO is not available for use in the child process. However, under OS/2 and under DOS
versions 3.0 and later, cmdname is available as argO.
The execl, execle, execlp, and execlpe calls are typically used when the number of argu­
ments is known in advance. The argument argO is usually a pointer to cmdname. The argu­
ments argl through argn point to the character strings forming the new argument list. A
null pointer must follow argn to mark the end of the argument list.
The execv, execve, execvp, and execvpe calls are useful when the number of arguments to
the new process is variable. Pointers to the arguments are passed as an array, argv. The ar­
gument argv[O] is usually a pointer to cmdname. The arguments argv[ l ] through argv[n]
point to the character strings forming the new argument list. The argument argv[n+ 1 ] must
be a NULL pointer to mark the end of the argument list.
Files that are open when an exec call is made remain open in the new process. In the execl,
execlp, execv, and execvp calls, the child process inherits the environment of the parent.
The execle, execlpe, execve, and execvpe calls allow the user to alter the environment for
the child process by passing a list of environment settings through the envp argument. The
argument envp is an array of character pointers, each element of which (except for the
final element) points to a null-terminated string defining an environment variable. Such a
string usually has the form
253 exec Functions

NAME=value
where NAME is the name of an environment variable and value is the string value to which
that variable is set. (Note that value is not enclosed in double quotation marks.) The final
element of the envp array should be NULL. When envp itself is NULL, the child process in­
herits the environment settings of the parent process.
A program executed with one of the exec family of functions is always loaded into
memory as if the "maximum allocation" field in the program's .EXE file header is set to
the default value of OFFFFH. You can use the EXEMOD utility to change the maximum
allocation field of a program; however, such a program invoked with one of the exec func­
tions may behave differently from a program invoked directly from the operating-system
command line or with one of the spawn functions.
The exec calls do not preserve the translation modes of open files. If the child process
must use files inherited from the parent, the setmode routine should be used to set the
translation mode of these files to the desired mode.
You must explicitly flush (using mush or flushall) or close any stream prior to the exec
function call.
Signal settings are not preserved in child processes that are created by calls to exec
routines. The signal settings are reset to the default in the child process.

Return Value The exec functions do not normally return to the calling process. If an exec function re­
turns, an error has occurred and the return value is - 1 . The errno variable is set to one of
the following values:

Value Meaning

E2BIG The argument list exceeds 128 bytes, or the space required for
the environment information ex"eeds 32K.
EACCES The specified file has a locking or sharing violation
(OS/2, and DOS versions 3.0 or later).
EMFILE Too many files open (the specified file must be opened to de­
termine whether it is executable).
ENOENT File or path name not found.
ENOEXEC The specified file is not executable or has an invalid
executable-file format.
ENOMEM Not enough memory is available to execute the child process;
or the available memory has been corrupted; or an invalid
block exists, indicating that the parent process was not allo­
cated properly.
exec Fu ctions 254

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

Because of differences in DOS versions 2.0 and 2. 1 , child processes generated by the exec
family of functions (or by the equivalent spawn functions with the P_OVERLAY argu­
ment) may cause fatal system errors when they exit. If you are running DOS 2.0 or 2. 1 ,
you must upgrade to DOS version 3.0 or later to use these functions.
Bound programs cannot use the exec family of functions in real mode.

See Also abort, atexit, exit, _exit, onexit, spawn functions, system

!
/ * E X E C . C : T h i s p r o g r a m a c cepts a n umbe r i n t h e r a n g e 1 t h ro u g h 8 f rom t h e
* c omma n d l i n e . B a s ed on t h e n umb e r i t r e c e i ves , i t executes one of t h e
* e i g h t d i f f e rent p r o c ed u re s t h a t s pawn t h e p r o c e s s n a med c h i l d . For
* s ome of these p r o c e d u r e s , t h e c h i l d . exe f i l e must be i n t h e s a m e
* d i r e c t o y ; for o t h e r s , i t need o n l y be i n t h e s a me p a t h .
*I

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


#i n c l ude < r o c e s s . h >


'!
c h a r *my_e v [ J = (
" TH I S=e n v i ronment wi l l be " ,
" PASS E D=to c h i l d . ex e by t h e " ,
" EX EC L E=a nd " ,
" EX E C L P E=a nd " ,
" E X E C V E=a n d " ,
" EX E C V P E=funct i on s • ,
NULL
I:

v o i d ma i n ( i n t a rg c , c h a r *a r g v [ J )
( I

T�
cha r *a s [4] :
i nt r e s u l t ;

a rg s [ 0 ] "chi l d " ; / * Set up pa rame t e r s t o s e n d * I


a rg s [ l ] " exec v ? ? " ;
a rg s [ 2 ] " two " ;
a rg s [ 3 ] NULL ;

I
I I
255 exec FuncUons

swi t c h ( a rg v [ 1 J [ 0 J ) / * Ba sed on f i r s t l et t e r of a rg ument * /


(
case ' 1 ' : ·

exec l ( a rg v [ 2 J , a rg v [ 2 ] , " ex e c l " , " two " , N U L L > :


brea k :
case ' 2 ' :
e x ec l e C a rg v [ 2 J , a rg v [ 2 J , " ex e c l e " , " tw o • , N U L L , my_env > :
b rea k ;
case ' 3 ' :
e x e c l p ( a r g v [ 2 ] , a rgv [ 2 ] , " ex e c l p " , " two " , N U L L ) ;
b r ea k ;
case ' 4 ' :
exec l p e ( a rg v [ 2 J , a rg v [ 2 J , " ex e c l p e " , " two • , N U L L , my_en v ) ;
b r ea k ;
ca s e ' 5 ' :
exec v C a rg v [ 2 J , a rg s ) ;
brea k ;
case ' 6 ' :
exec v e C a rg v [ 2 J , a rg s , my_e n v ) ;
b rea k ;
case ' 7 ' :
e x ec v p C a rg v [ 2 J , a rg s > :
b r ea k ;
ca s e ' 8 ' :
e x e c v p e ( a rg v [ 2 ] , a rg s , my_en v ) ;
b r ea k ;
d e fa u l t :
p r i n t f ( " SY NTAX : E X E C < 1 -8> < c h i l d p r o g r a m> \ n " ) ;
exi t C 1 > ;
)
p r i nt f C " P ro c e s s wa s not s p a wned . \ n " ) ;
p r i ntf ( " P ro g ram ' c h i l d ' wa s not found . " ) ;
Dat:ripllon Tenninate the calling process after cleanup (exit) or immediately ( _exit).

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


#include <Stdlib.h> Use either PROCESS.ff or STDLIB.H

void exit( int status );


void _exit( int status );

status Exit status

Remal'ks The exit and _exit functions tenninate the calling process. The exit function first calls, in
LIFO (last-in-first-out) order, the functions registered by atexit and onexit, then flushes
all file buffers before tenninating the process. The _exit function tenninates the process
without processing atexit or onexit functions or flushing stream buffers. The status value
is typically set to 0 to indicate a nonnal exit and set to some other value to indicate an
error.
Although the exit and _exit calls do not return a value, the low-order byte of status is
made available to the waiting parent process, if one exists, after the calling process exits.
The status value is available to the operating-system batch command ERRORLEVEL.
The behavior of the exit, _exit, _cexit, and _c_exit functions is as follows:
Function Action

exit Perfonns complete C library tennination procedures, tenni­


nates the process, and exits with the supplied status code.
_exit Perfonns "quick" C library tennination procedures, tenninates
the process, and exits with the supplied status code.
_cexit Perfonns complete C library tennination procedures and re­
turns to caller, but does not tenninate the process.
c exit Perfonns "quick" C library tennination procedures and re­
turns to c aller, but does not tenninate the process.
257 exit, _exit

Return Value None.

Compatibility exit

• ANSI • DOS • OS/2 • UN IX • XENIX

exit

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

See Also abort, atexit, _cexit, exec functions, onexit, spawn functions, system

I * E X I T E R . C : T h i s p r o g r a m p rompts t h e u s e r f o r a y e s o r n o a n d re t u r n s
* a DOS e r r o r c o d e o f 1 i f t h e u s e r a n swers Y o r y ; o t h e rw i s e i t
* r e t u r n s 0 . T h e e r r o r code c o u l d be tested i n a b a t c h f i l e .
*/

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


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

v o i d ma i n ( )
(
char ch ;

cputs ( " Y es or no? " ) ;


c h = getc h ( ) ;
cputs ( " \ r\ n " ) ;
i f ( touppe r ( c h ) 'Y' >
ex i t ( 1 > ;
el se
ex i t ( 0 ) ;
I

exp, ex / �I 258

Description I Calculate the exponential.

#include <math.h>

double exp( double x );


long double expl( long double x );

x Floating-point value

Remarks The exp and expl functions return the exponential function of their floating-point argu­
ments (x).
The expl function is the 80-bit counterpart; it uses an 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 These functions return ex. The functions return HUGE_VAL on overflow and set errno to
ERANGE; on underflow, they return 0 but do not set errno.

Compatibility exp

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

expI

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

See Also log functions

i
I* EXP . C */
#i n c l u d e <ma t h . h>
#1 n c 1 " d e < d 1 o . h>
259 exp, exp/

v o i d ma i n ( )
(
d o u b l e x = 2 . 30258509 3 , y;

y = ex p ( x l ;
p r i n t f ( • ex p ( % f l = % f \ n " , x , y l;

Output

exp ( 2 . 302 585 l = 10 . 000000


I
I
I

_expan Functions 260

Description Changes the size of a memory block.

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

void *_expand( void *memblock, size_t size );


void _based( void ) *_bexpand( _segment seg, void _based( void ) *memblock,
size_t size );
void _far *_fexpand( void _far *memblock, size_t size ) ;
void _near *_nexpand( void _near *memblock, size_t size );

memblock Pointer to previously allocated memory block

size New size in bytes

seg Value of base segment

Remarks The _expand family of functions changes the size of a previously allocated memory block
by attempting to expand or contract the block without moving its location in the heap. The
memblock argument points to the beginning of the block. The size argument gives the new
size of the block, in bytes. The contents of the block are unchanged up to the shorter of the
new and old sizes.
The memb/ock argument can also point to a block that has been freed, as long as there has
been no intervening call to calloc, _expand, malloc, or realloc. If memblock points to a
freed block, the block remains free after a call to one of the _expand functions.
The seg argument is the segment address of the _based heap.
In large data models (compact-, large-, and huge-model programs), _expand maps to
_fexpand. In small data models ( tiny-, small-, and medium-model programs), expand
maps to _nexpand.

The various _expand functions change the size of the storage block in the data segments
shown in the list below:
Function Data Segment

_expand Depends on data model of program

_bexpand Based heap specified by seg, or in all based heaps if seg


is zero

_fexpand Far heap (outside default data segment)

_nexpand Near heap (inside default data segment)


261 _expand Functions

Return Value The _expand family of functions returns a void pointer to the reallocated memory
block. Unlike realloc, _expand cannot move a block to change its size. This means the
memblock argument to _expand is the same as the return value if there is sufficient
memory available to expand the block without moving it.
With the exception of the _bexpand function, these functions return NULL if there is in­
sufficient memory available to expand the block to the given size without moving it. The
_bexpand function returns _NULLOFF if insufficient memory is available. The item
pointed to by memblock will have been expanded as much as possible in its current
location.
The storage space pointed to by the return value is guaranteed to be suitably aligned for
storage of any type of object. The new size of the item can be checked with the _msize
function. To get a pointer to a type other than void, use a type cast on the return value.

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

See Also calloc functions, free functions, malloc functions, _msize functions, realloc functions

Exampm ��
��

/ * EX PAND . C * /
#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>
#i n c l u d e < s t d l i b . h>

v o i d ma i n ( )
(
c h a r *bufc ha r ;

p r i n t f ( " Al l o c a t e a 5 1 2 e l eme n t buff e r \ n " ) ;


i f ( ( b ufc h a r = ( c h a r * ) c a l l oc ( 5 1 2 , s i z e o f ( c h a r ) ) ) == NULL )
exi t ( 1 ) ;
p r i n t f ( " A l l o c a t e d %d byt e s a t % F p \ n " ,
_ms i z e ( bufc h a r ) , ( v o i d _fa r * ) b u fc h a r ) ;

i f ( C b u fc h a r = ( c h a r * )_expa nd ( b u f c h a r , 1024 ) ) == NULL )


p r i n t f ( " C a n ' t expa n d " > :
el se
p r i n t f ( " Expa n d ed b l o c k t o %d by tes a t % F p \ n " ,
_ms i ze ( bufc h a r ) , ( v o i d _fa r * ) b u fc h a r > :

I * Free memo ry * /
f r e e ( b u fc h a r ) ;
exi t ( 0 ) :
1 I
_expan Functions 262

Output


Al l o c a t e a 1 2 el ement buffer
Al l o c a t e d 5 2 by tes a t 0067 : 142A
Expa nded bl c k to 1024 by tes a t 0067 : 142A
263 labs, labs/

DllSCtlpllan Calculate the absolute value of their floating-point arguments.

#include <math.h>

double fabs( double x );


long double fabsl( long double x );

x Floating-point v alue

Remalks The fabs and fabsl functions calculate the absolute value of their floating-point arguments.
The fabsl function is the 80-bit counterpart; it 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.

Relum Value These functions return the absolute value of their arguments. There is no error return.

Campallbillty fabs

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

fabsl

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

See Also abs, cabs, 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 ays t h e a b s o l u t e v a l ues o f


* s ev e r a l numbe rs .
*/

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


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

I
v o i d ma i n ( ) I
1 XI = - 4 , 1 y ;
1 ·
.
·
1 nt
h
l ong
j -41567 L , l y ;
=

d o u b l e d = - 3 . 1 4 1 5 9 3 , dy ;

t
i y = abs ( i x l ;
p r i n t f ( T h e a b s o l ute v a l ue o f %d i s % d \ n " , i x , i y ) ;

p r i n t f ( h h e a b s o l ute v a l ue o f % l d i s %l d \ n " , l x , l y l ;
l y = l a b$ < l x l :

l
dy = f a b� ( dx l ;
p r i n t f ( T h e a b s o l ute v a l ue of %f i s %f\ n " , dx , d y l ;

Output
I
T h e a b s o l ut � v a l ue o f -4 i s 4

t
T h e a bs o l ute v a l ue o f - 4 1 567 i s 4 1 5 6 7
T h e a bs o l u t v a l ue o f - 3 . 1 4 1 5 9 3 i s 3 . 1 4 1 5 9 3
265 fclose, fcloseall

Descrlpl/on Closes a stream (fclose) or closes all open streams (fcloseall).

#include <Stdio.h>

int fclose( FILE *stream );


int fcloseall( void );

stream Pointer to FILE structure

Remarks The fclose function closes stream. The fcloseall function closes all open streams except
stdio, stdout, stderr (and in DOS, stdaux and stdprn). It also closes and deletes any tem­
porary files created by tmpfile.
In both functions, all buffers associated with the stream are flushed prior to closing.
System-allocated buffers are released when the stream is closed. Buffers assigned by the
user with setbuf and setvbuf are not automatically released.

Return Value The fclose function returns 0 if the stream is successfully closed. The fcloseall function re­
turns the total number of streams closed. Both functions return EOF to indicate an error.

Compallblllty fclose

• ANSI • DOS • OS/2 • U N IX • XEN IX

fcloseall

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

See Also close, fdopen, mush, fopen, freopen

/ * FO P E N . C : T h i s p r o g r a m o p e n s f i l e s n a med " d a t a " a nd " d a t a 2 " . I t u s e s


* f c l o s e t o c l o s e " d a t a " a n d f c l o s e a l l t o c l o s e a l l rema i n i n g f i l e s .
*I

#i n c l u d e < s t d i o . h >
!close, �closeall 266

1I
F I L E * s t r a m , * s t ream2 ;

C1
v o i d ma i n >
{ I
i nt n ull!c l o s ed ;

1
i f ( < s � ream
I * Ope f o r r e a d ( w i l l fa i l i f ' d a t a d o e s not e x i s t ) * /
fopen < " d a t a • , • r • ) )
= NULL )
=

J
p r i t f ( " T h e f i l e ' d a ta ' wa s not opened \ n " > :
el s e

1
p r i t f ( " T h e fi l e ' d a t a ' w a s opened \ n " ) ;

1
I * Ope for wri te * /
i f ( < s r e a m2 = fopen ( " da t a 2 " , • w+• ) ) == N U L L
p r i t f ( " T h e f i l e ' da t a 2 ' wa s n o t opened \ n " > :
el s e

l
p r i ntf ( " T h e f i l e ' d a t a 2 ' wa s opened \ n " > :

/ * C l o � e s t re a m * /
i f ( f c ' os e ( s t re a m )
p r i t f ( " T h e f i l e ' d a ta ' wa s not c l o s ed \ n " > :

I * Al l ot h e r f i l e s a re c l o s e d : * /


numc l o sed f c l o s ea l l ( ) ;
=

p r i n t f " N umbe r of f i l es c l o s e d by fc l os ea l l : % u \ n " , n umc l o s e d ) ;

I
I
Output


T h e fi l e · a t a ' wa s opened
T h e f i l e ' d a t a 2 ' wa s opened
N umber o f , f i l e s c l o s e d by f c l o s e a l l : 1
267 fcvt

Description Converts a floating-point number to a string.

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

char *fcvt( double value, int count, int *dee, int *sign );

value Number to be converted


count Number of digits after decimal point
dee Pointer to stored decimal-point position
sign Pointer to stored sign indicator

Remarks The fcvt function converts a floating-point number to a null-terminated character string.
The value argument is the floating-point number to be converted. The fcvt function stores
the digits of value as a string and appends a null character ('\0'). The count argument speci­
fies the number of digits to be stored after. the decimal point. Excess digits are rounded off
to count places. If there are fewer than count digits of precision, the string is padded with
zeros.
Only digits are stored in the string. The position of the decimal point and the sign of value
can be obtained from dee and sign after the call. The dee argument points to an integer
value; this integer value gives the position of the decimal point with respect to the begin­
ning of the string. A zero or negative integer value indicates that the decimal point lies to
the left of the first digit. The argument sign points to an integer indicating the sign of
value. The integer is set to 0 if value is positive and is set to a nonzero number if value is
negative.
The ecvt and fcvt functions use a single statically allocated buffer for the conversion. Each
call to one of these routines destroys the results of the previous call.

Return Value The fcvt function returns a pointer to the string of digits. There is no error return.

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

See Also atof, atoi, atol, ecvt, gcvt

I*I** setsFCVT . theC : Thispoi nterprogr*buffer


Example
am convertsto poithent toconstathatntstri ng. to a stri ng and
____________________________________________________________________

3 . 1415926535
268


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

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

v o i d ma i n O
(
i n t d e i ma l , s i g n :
c h a r *b ffe r :
doubl e ource = 3 . 141 5926535 :

buffer fc v t ( s o u rc e , 7 , &de c i ma l , &s i g n > :


p r i n t f ( " s o u rc e : % 2 . 1 0 f b u f fe r : ' % s ' d e c i ma l : %d s i gn : %d\n " ,
s o u r ce , b u f f e r , d ec i ma l , s i g n > :

Output

s o u rce : 3 . 1 4 1 5 9 2 6 5 3 5 buffe r : ' 3 1 4 1 5927 ' d ec i ma l : 1 s i gn : 0


269 Idopen

Description Opens a stream using a handle.

#include <Stdio.h>

FILE *fdopen( int handle, char *mode );

handle Handle referring to open file


mode TYpe of access pennitted

Remarks The fdopen func�ion associates an input/output stream with the file identified by handle,
thus allowing a file opened for "low-level" 1/0 to be buffered and fonnatted. (See Section
2.7, "Input and Output," for an explanation of stream 1/0 and low-level 1/0.) The mode
character string specifies the type of access requested for the file, as shown below. The fol­
lowing list gives the mode string used in the fopen and fdopen functions and the corre­
sponding oflag arguments used in the open and sopen functions. A complete description
of the mode string argument is given in the remarks section of the fopen function.

Type String Equivalent Value for open/sopen


" r" O_RDONLY
" w" O_WRONLY (usually O_WRONLY I O_CREAT I o_TRUNC)
" a" O_WRONLY I O_APPEND (usually O_WRONLY I O_CREAT I
O_APPEND)
" r+" O_RDWR
" w+" o_RDWR (usually O_RDWR I o_CREAT I O_TRUNC)
" a+ " O_RDWR I O_APPEND (usually o_RDWR I O_APPEND I
O_CREAT )

In addition to the values listed above, one of the following characters can be included in
the mode string to specify the translation mode for newlines. These characters correspond
to the constants used in the open and sopen functions, as shown below:

Mode Equivalent Value for open/sopen


t O_TEXT
b O_BINARY

If t or b is not given in the mode string, the translation mode is defined by the default­
mode variable _fmode.
fdapen 270

The t option is not part of the ANSI standard for fopen and fpopen, but is instead a
Microsoft extension and should not be used where ANSI portability is desired.

Return Value The fdopen function returns a pointer to the open stream. A null pointer value indicates an
error.

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

See Also dup, dup2, fclose, fcloseall, fopen, freopen, open

I * FDO P E N . C 1 T h i s p r o g r a m opens a f i l e u s i ng l ow - l e v e l I / O , t h e n u s e s
* fdopen t swi t c h t o s t ream a c c e s s . I t c o u n t s t h e l i n e s i n t h e f i l e .
*I

#i n c l ude <s dl i b . h>


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

�oi d ma i n ( )

I
F I L E * s t e a rn :
i nt f h , c o u n t = 0 ;
c h a r i nb f [ 128J ;

I * Open f i l e h a nd l e . */
i f ( ( fh open ( " fdopen . c " , O_RDON LY ) ) == - 1
exit ( 1 ) :

I * C h a n g h a n d l e a c c e s s to s t r e a m a c c e s s . * /
i f ( C s t r a m = fdopen ( f h , • r • ) ) � NULL )
exi t ( 1 ) :

tt s (
[
whi l e( f i n b u f , 1 28 , s t ream ) ! = N U L L
count :

I
271 fdopen

I * Aft e r f d o p e n , c l o s e w i t h fc l o s e , n o t c l o s e . */
fc l os e { s t ream > :

pri ntf{ " Li nes i n fi l e : %d\ n " , count > :

Output

Li nes i n fi l e : 31
feat 272

Description I Tests for end-of-file on a stream.

#include <stdio.h>

int feof( FILE *stream );

stream Pointer to FILE structure

Remarks The feof routine (implemented as a macro) determines whether the end of stream has been
reached. Once the end of the file is reached, read operations return an end-of-file
indicator until the stream is closed or until rewind, fsetpos, fseek, or clearerr is called
i
against it.
I

Return Vala � The feof function returns a nonzero value after the first read operation that attempts to read
past the end of the file. It returns 0 if the current position is not end-of-file. There is no

I
error return.

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

See Also clearerr, eof, ferror, perror

Exampre ___.���

I * F EO F . C l T h i s p r o g r a m u s e s feof t o i n d i c a t e when i t rea c h e s t h e end


* of the f i l e F E O F . C . It a l s o c h e c ks f o r e r r o r s w i t h ferr o r .

I
*I

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

v o i d ma i n ( )
i I
i nt crunt , tota l = 0;
c h a r b � f fe r [ 1 0 0 J ;
F I LE *� tream ;

i f ( < s t r e a m = fopen ( " f eof . c · , " r " ll NULL l


exi t ( 1 l ;
273 feat

I * Cycl e un t i l end o f f i l e rea c h ed : * /


w h i l e ( ! feof ( s t r e a m ) )
{
I * Att empt t o r e a d i n 1 0 byt e s : * /
count = f r ea d ( b u f fe r , s i zeof ( c h a r ) , 100 , st ream > :
i f ( f e r ro r ( st ream ) )
{
p e r ro r ( " Re a d e r r o r " ) ;
b r ea k ;

I * Tot a l u p a c t u a l byt e s r e a d * /
t ot a l +- c ount :
)
p r i n t f { " N umb e r o f byt e s read = Sd \ n " , tota l > ;
f c l o s e < s t ream > :

Output

Numb e r of byt e s r e a d = 6 9 7
terror 274

Dll8t:rlpl/on Tests for an error on a stream.

#include <Stdio.h>

int ferror( FILE *stream );

stream Pointer to FILE structure

Remarks The ferror routine (implemented as a macro) tests for a reading or writing error on the file
associated with stream. If an error has occurred, the error indicator for the stream remains
set until the stream is closed or rewound, or until clearerr is called against it.

Return Value If no error has occurred on stream, ferror returns 0. Otherwise, it returns a nonzero value.

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

See Also clearerr, eof, feof, fopen, perror

I * F E O F . C : h i s p r o g r a m u s e s feof to i n d i c a t e when i t r e a c hes t h e end


* o f the f l e F E O F . C . It a l s o checks f o r errors w i t h f e r r o r .
*/

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


#i n c l ude < s d l i b . h >
i
v o i d ma i n ( )
(
i n t c o u t , tot a l = 0 ;
c h a r b u f e r [ 100 ] ;
F I L E * s t e a rn :

i f ( C s t r a m = fopen C " feo f . c " , • r • > > == N U L L >


exi t ( 1 > :
275 terror

I * Cyc l e u n t i l end of f i l e rea c h ed : * /


w h i l e ( l feof ( s t ream ) )
[
I * Att empt t o r e a d i n 1 0 byt e s : * /
count m frea d ( buffe r , s i z e o f C c h a r ) , 100 , s t ream ) ;
i f ( f e r ro r ( s t ream ) )
[
p e r ro r ( " Re a d e r ro r • ) ;
brea k ;

I * Tot a l u p a ct u a l byt e s rea d * /


tota l +m count ;
}
p r i n t f C " N umbe r of byt e s read = Zd\ n " , t ot a l ) ;
fc l os e ( s t ream ) ;

Output

N umber of byt e s r e a d D 697


fllush 276

Description Flushes a stream.

#include <Stdio.h>

int mush( FILE *stream );

stream Pointer to FILE structure

Remarks If the file associated with stream is open for output, mush writes to that file the contents
of the buffer associated with the stream. If the stream is open for input, mush clears the
contents of the buffer. The mush function negates the effect of any prior call to ungetc
against stream.
Buffers are automatically flushed when they are full, when the stream is closed, or when a
program terminates normally without closing the stream.
The stream remains open after the call. The mush function has no effect on an unbuffered
stream.

Return Value 1 The mush function returns the value 0 if the buffer was successfully flushed. The value 0
is also returned in cases in which the specified stream has no buffer or is open for reading
only. A return value of EOF indicates an error.

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

See Also I fclose, flushall, setbuf

/ * FFLUSH . C */
#i n c l ude < s d i o . h >
#i n c l ude < c n i o . h >

; ' ' ; :; : ; ; 1 : 1 . 1 :
211 fflush

/ * Read ea c h word a s a s t r i ng . * /
p r i n t f C " En t e r a s e n t e n c e of f o u r words w i t h s c a n f : • > :
fo r e i n t e g e r 0 ; i n t e g e r < 4 ; i n teger++ >
(
=

s c a n f C " %s " , s t r i n g > :

I*
pri ntfC "%s\n " , stri ng > :

Y o u mu s t f l u s h t h e i n put buffer before u s i n g gets . * /


ffl u s h ( s td i n > :
p r i n t f C " En t e r t h e s a me sentence w i t h gets : • > :
g et s ( s t r i n g > :
pri ntfC "%s\ n " , stri ng > :

Output

E n t e r a s e n t e n c e of f o u r w o r d s w i t h s c a n f : T h i s i s a t e s t
Thi s
is
a
test
E n t e r t h e s a me s entence w i t h gets : T h i s i s a t e s t
Thi s i s a test
tgett:, fgttt:har I
218

Description Read a character from a stream (fgetc) or stdin (fgetchar).

#include <Stdio.h>

int fgetc( FILE *stream );


int fgetchar( void );

stream Pointer to FILE structure

Rematits The fgetc function reads a single character from the current position of the file associated
with stream. The character is converted and returned as an int The function then incre­
ments the associated file pointer (if any) to point to the next character. The fgetchar func­
tion is equivalent to fgetc(stdin).
The fgetc and fgetchar routines are identical to getc and getchar, but they are functions
rather than macros.

Retum Value The fgetc and fgetchar functions return the character read. They return EOF to indicate an
error or end-of-file. Use feof or ferror to distinguish between an error and an end-of-file
condition. ·

Campallbll/ly fgetc

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

fgetchar

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

See Also fputc, fputchar, getc, getchar

l
Exampm
!
__ -+------------------------------------------------------------------------------------------------------------------------ -

1 * FG ETC . C : T h i s p r o g r a m u s e s getc t o r e a d t h e f i r s t 80 i n put c h a r a c t e rs


* C o r u n t i l t h e e n d of i n put ) a n d p l a c e t h em i n to a s t r i n g n a med buffer .
*I

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


/Ii n c l ude < s tld l i b . h >

I
279 fgetc, fgetchar

v o i d ma i n ( )
{
F I L E * s t re a m ;
c h a r buffe r [ 8 1 ] ;
i nt i , ch ;

I * Open f i l e t o rea d l i ne from : * /


i f ( < s t re a m = fopen C " fg e t c . c • , • r • ) ) == N U L L )
exi t ( 0 ) ;

I * Read i n f i r s t 80 c h a r a c t e r s a n d p l a c e t h em i n " b uffer " : * /


c h = fget c ( s t ream ) ;
fo r e i =0 ; C i < 80 ) && C feof C s t re a m ) == 0 ) ; i ++ )
{
buffer [ i ] = c h ;
c h = fgetc C s t re a m ) ;
)
I * Add n u l l t o end s t r i n g * /
buffe r [ i l = ' \0 ' ;
p r i n t f C " % s \ n " , buffer ) ;
fcl o s e C st ream ) ;

Output

I * FGETC . C : T h i s p r o g r a m u s e s getc to read t h e f i r s t 80 i n put c h a r a c t e r s


I* C or
fgetpas 280

Dest:rlptlan Gets a stream's file-position indicator.

#include <Stdio.h>

int fgetpos( FILE *stream, fpos_t *pos );

stream Target stream

pos Position-indicator storage

Rematks The fgetpos function gets the current value of the stream argument's file-position indicator
and stores it in the object pointed to by pos. The fsetpos function can later use infonnation
stored in pos to reset the stream argument's pointer to its position at the time fgetpos was
called.

The pos v alue is stored in an internal fonnat and is intended for use only by the fgetpos
and fsetpos functions.

Return Value If successful, the fgetpos function returns 0. On failure, it returns a nonzero value and sets
errno to one of the following manifest constants (defined in STDIO.H):

Constant Meaning

EBADF The specified stream is not a valid file handle or is not


accessible.

EINVAL The stream value is invalid.

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

See Also fsetpos

/ * FGETPO S . � : T h i s p r o g r a m opens a f i l e a nd r e a d s byt e s a t s e v e ra l


* d i fferen � l oc a t i o n s .
I
*I

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


281 fgetpos

v o i d ma i n ( )
(
FI LE * s t rea m ;
f p o s_t p o s ;
i nt val ;
cha r b u f fe r [ 20 ] ;

i f( ( s t r e a m = f o p e n < " f g e t p o s . c " , " rb " ) ) == N U L L )


p r i n t f ( " Troubl e open i ng f i l e\ n " > :
el se
(
I * R e a d s ome d a t a a n d t h e n c h e c k t h e p o s i t i o n . * /
f r ea d C b u f f e r , s i z e o f ( c h a r ) , 1 0 , s t r e a m > :
i f ( fgetpos ( st ream , &pos > ! = 0 >
pe r r o r ( " fgetpos e r r o r " ) ;
el s e
I
frea d ( buffe r , s i zeof ( c h a r ) , 10 , s t ream > :
p r i n t f ( " 1 0 by t e s a t by t e % l d : % . 1 0 s \ n " , p o s , b u f f e r ) ;

I * S e t a n ew p o s i t i o n a n d r e a d mo r e d a t a * /
p o s = 140 ;
i f ( fsetpo s ( s t ream , &pos ) ! = 0 )
p e r ro r < " fsetpos e r ro r " > :

f r e a d ( b u f fe r , s i z e o f ( c h a r ) , 1 0 , s t r e a m > :
p r i n t f ( " 1 0 by t e s a t by t e % l d : % . 1 0 s \ n " , p o s , b u f f e r > :

f c l o s e ( s t re a m ) ;

Output

1 0 by t e s a t by t e 1 0 : .C: Thi s p
10 bytes a t byte 140 : FI LE *
fgets 282

Description Gets a string from a stream.

#include <Stdio.h>

char *fgets( char *string, int n, FILE *stream );

string Storage location for data

n Number of characters stored

stream Pointer to FILE structure

RemalkB The fgets function reads a string from the input stream argument and stores it in string.
Characters are read from the current stream position up to and including the first newline
character ('\n '), up to the end of the stream, or until the number of characters read is equal
to n 1 , whichever comes first. The result is stored in string, and a null character ('\0') is
-

appended. The newline character, if read, is included in the string. If n is equal to l , string
is empty ( " "). The fgets function is similar to the gets function; however, gets replaces the
newline character with NULL.

Retum Value If successful, the fgets function returns string. It returns NULL to indicate either an error or
end-of-file condition. Use feof or ferror to determine whether an error occurred.

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

See Also fputs, gets, puts

I* FGETS . C : T i s p rog ram u s e s fgets to d i s p l ay a l i n e f r om a fi l e on t h e


* s c reen .
*I
I
#i n c l ude < s t d f o . h>

F I L E * s t re a m ;

v o i d ma i n ( )
{
c h a r l i n e [ 0 0 ] , * res u l t ;
283 !gets

i f ( ( st r e a m = fopen C " fg e t s . c • , • r • ) ) ! = N U L L
(
i f ( fget s ( l i n e , 100 , s t re a m l == NU L L )
p r i n t f ( " fgets e r r o r \ n " > :
el se
pri ntf( " %s " , 1 i ne l :
fc l o s e ( s t ream > :

Output

I * FGETS . C : T h i s p r o g r a m u s e s fgets t o d i s p l a y a l i n e f rom a f i l e o n t h e


tiseeto rI
in, tmsbintoieee 284

Dest:rlplion Convert floating-point numbers between IEEE and Microsoft binary fonnats.
I
I
#include <math.h>

I
int fieeetomsbin( float *src4, float *dst4 );
int fmsbintoieee( float *src4, float *dst4 );

scr4 Value to be converted

dst4 Converted value

Remades The fieeetomsbin routine converts a single-precision floating-point number in IEEE (Insti­
tute of Electrical and Electronic Engineers) fonnat to Microsoft (MS) binary fonnat.

The fmsbintoieee routine converts a floating-point number in Microsoft binary fonnat to


IEEE format.

These routines allow C programs (which store floating-point numbers in the IEEE fonnat)
to use numeric data in random-access data files created with Microsoft BASIC (which
stores floating-point numbers in the Microsoft binary fonnat), and vice versa.

The argument src4 points to the float value to be converted. The result is stored at the loca­
tion given by dst4.

These routines do not handle IEEE NANs ("not a number") and infinities. IEEE denonnals
are treated as 0 in the conversions.

Retum Value These functions return 0 if the conversion is successful and 1 if the conversion causes an
overflow.

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

See Also dieeetomsbin, dmsbintoieee


285 filelength

Description Gets the length of a file.

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

long filelength( int handle );

handle Target file handle

Remarks The filelength function returns the length, in bytes, of the target file associated with
handle.

Return Value The filelength function returns the file length in bytes. A return value of - I L indicates an
error, and an invalid handle sets errno to EBADF.

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

SIJIJ A/so chsize, fileno, fstat, stat

I * C H S I Z E . C : T h i s p r o g r a m u s e s f i l e l ength t o report t h e s i z e of a
* f i l e before a nd a ft e r mod i fy i n g i t w i t h c h s i z e .
*I

//i n c l ude < i o . h>


#i n c l ude <fcntl . h>
#i n c l ude < sy s \ types . h >
#i n c l ude < s y s \ s ta t . h >
#i n c l ude <stdi o . h>

v o i d ma i n ( )
(
i n t f h , res u l t ;
u n s i gned i nt n by t e s = BUFSI Z :
286


open ( " d a ta " , O_RDWR I O_C R EAT , S_I READ I S_I W R I T E ) ) ! = - 1 )

1
I * Open fi l e */
i f ( ( fh r
1 pri nt �< " F i l e l en g t h before : z 1 d \ n " , f i l e l en gt h < fh ) ) ;

f
if( c s i ze( fh , 329678 ) � 0 >
pr n t f { " S i z e s u c c e s s f u l l y c h a n g ed \ n " > ;
el se
pr n t f ( " P robl em i n c h a n g i n g t h e s i z e \ n " ) ;
pri nt ( " Fi l e l en g t h a ft e r : % l d \ n " , f i l e l engt h ( fh ) ) ;
cl ose fh > ;

) I

I
r\
Output

F i l e l en g t h before : 0
S i z e s u c c e s f u l l y c h a nged
F i l e l en g t h a ft e r : 329678

I
I
287 fileno

Dest:rlpllon Gets the file handle associated with a stream.

#include <Stdio.h>

int fdeno( FILE *stream );

stream Pointer to FILE structure

Remal'ks The fileno routine returns the file handle currently associated with stream. This routine is
implemented as a macro.

Retum Value The fileno routine returns the file handle. There is no error return. The result is undefined
if stream does not specify an open file.

Compaliblllty 0 ANSI • DOS • OS/2 • U N IX • XENIX

See Also fdopen, filelength, fopen, freopen

I * F I L E N O . C : T h i s p r o g r a m u s e s fi l eno to obta i n t h e f i l e h a n d l e f o r
* s ome s t a n d a rd C s t reams .
*I

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

v o i d ma i n ( )
{
p r i ntf C " T h e fi l e h a n d l e f o r s t d i n i s % d \ n " , f i l en o C s td i n ) ) ;
p r i ntf ( " T h e f i l e h a n d l e f o r s t d o u t i s %d \ n " , f i l e n o C s t d o u t > ) ;
p r i n t f ( " T h e f i l e h a n d l e f o r s t d e r r i s %d \ n " , f i l eno ( s t d e r r ) ) ;

Output

T h e f i l e h a n d l e for s td i n i s 0
T h e f i l e h a n d l e fo r s t d o u t i s 1
T h e f i l e h a n d l e fo r s t d e r r i s 2
_floodfill, floodfill_w 288

Descrlpllan Fill an area of a display using the current color and fill mask

#include <graph.h>

short _far _floodfill( short x, short y, short boundary );


short _far _floodfill_w( double wx, double wy, short boundary );

x, y Start point

wx, wy Start point


boundary Boundary color of area to be filled

Remarks The functions in the _floodfill family fill an area of the display, using the current color and
fill mask. The _ftoodfill routine begins filling at the view-coordinate point (x, y). The
_floodfill_w routine begins filling at the window-coordinate point (wx, wy).
If this point lies inside the figure, the interior is filled; if it lies outside the figure, the back­
ground is filled. The point must be inside or outside the figure to be filled, not on the fig­
ure boundary itself. Filling occurs in all directions, stopping at the color of boundary.

Retum Value The floodfill functions return a nonzero value if the fill is successful. It returns 0 if the fill
could not be completed, the starting point lies on the boundary color, or the start point lies
outside the clipping region.

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

See Also _ellipse functions, _getcolor, _getfillmask, _grstatus, _pie functions, _setfillmask,
_setcliprgn, _setcolor

I * F LOOD F I L . C � T h i s p r o g r a m d r aws a s e r i es of n e s t ed recta n g l es i n


* d i fferent 9 o l o r s , c o n s t a n t l y c h a n g i n g t h e b a c k g r o u n d c o l o r .

i
*I
I
I

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

I
I
289 _lloodfill, _lloodfill_w

v o i d ma i n ( )
(
i n t l oop ;
i nt xva r , yva r ;

I * f i n d a v a l i d g r a p h i c s mod e * /
i f ( ! _s et v i d eomod e ( _MA X C O LO RMODE l l
exi t ( 1 l ;

fo r ( x v a r = 1 6 3 , l o op = 0 ; x v a r < 320 ; l oop++ , x v a r += 3 l


(
_s e t c o l o r ( l oop % 1 6 l ;
yva r = xva r * � I 8 ;
_re c t a n g l e ( _GBO RD E R , 320 - x v a r , 200-y v a r , x v a r , y v a r l ;
_s e t c o l o r ( r a n d ( ) % 1 6 ) ;
_fl oodfi l l ( 0 , 0 , l oop % 1 6 ) ;
}
getc h ( l ;
_s e t v i d e omod e ( _D E FAU LTMODE ) ;
I
floor, flo�rl 2so

Description Calculate the floor of a value.

#include <math.h>

double floor( double x );


long double floorl( long double x );

x Floating-point value

Remarks The floor and floorl functions return a floating-point value representing the largest integer
that is less than or equal to x.
The floorl function is the 80-bit counterpart, and it uses the 80-bit, I O-byte coprocessor
fonn of arguments and return values. See the reference page on the long double functions
for more details on this data type.

Return Value These functions return the floating-point result. There is no error return.

Compal/blllty floor

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

floorI

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

See Also ceil, fmod

I * F LOOR . C : T h i s examp l e d i spl a y s t h e l a rg e s t i n t e g e r s l e s s t h a n o r equa l


* t o t h e f l � a t i n g - p o 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 st
* i nt e g e r s g r e a t e r t h a n o r equa l t o 2 . 8 a n d - 2 . 8 .
*/
i

{
#i n c l u d e <ma h . h >
# i n c l u d e < s t� i o . h >
291 floor, floor/

v o i d ma i n ( }
(
doubl e y ;

y = fl oo r ( 2 . 8 > :
p r i ntf( "The fl oor of 2 . 8 i s %f\n " , y > :
y = fl oo r c · - 2 . 8 > :
p r i ntf ( " T h e fl oor o f - 2 . 8 i s %f\ n " , y } ;

y = cei 1 ( 2 .8 ) :
p r i n t f ( " T h e c e i l of 2 . 8 i s % f \ n � . y > :
y = cei l ( -2 . 8 > :
p r i n t f ( " T h e c e i l of - 2 . 8 i s % f \ n " , y > :

Output

The fl o o r of 2 . 8 i s 2 . 000000
The fl o o r o f - 2 . 8 i s - 3 . 000000
The c e i l o f 2 . 8 i s 3 . 000000
The c e i l o f - 2 . 8 i s - 2 . 000000
llushall 292

Dut:rlpUan Flushes all streams; clears all buffers.

#include <Stdio.h>

int flushall( void );

Rematits The flushall function writes to its associated files the contents of all buffers associated
with open output streams. All buffers associated with open input streams are cleared of
their current contents. The next read operation (if there is one) then reads new data from
the input files into the buffers.
Buffers are automatically flushed when they are full, when streams are closed, or when a
program terminates normally without closing streams.
All streams remain open after the call to flushall

Retum Value The flushall function returns the number of open streams (input and output). There is no
error return.

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

See Also mush

f.
I * F L U S HA L L . : T h i s p ro g r a m u s e s fl u s h a l l t o fl u s h a l l open buffe r s . * /

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

v o i d ma i n ( )
(
i n t n umfl s h ed ;

n umfl u s h e =fl u s h a l l ( ) ;
p r i n t f ( • h e r e w e r e Sd s t reams fl u s he d \ n " , n umfl u s hed ) ;

Output

T h e r e were 'II s t reams fl u s hed


293 fmod, fmodl

Description Calculates the floating-point remainder.

#include <math.h>

double fmod( double x, double y );


long double fmodl( long double x, long double y );

x, y Floating-point values

Remarks The fmod and fmodl functions calculate the floating-point remainderf of x I y such that
x = i * y + f, where i is an integer, f has the same sign as x, and the absolute value of f is

less than the absolute value ofy.


The fmodl function is the 80-bit counterpart; it uses the 80-bit, 10-byte coprocessor form
of arguments and return values. See the discussion of the long double functions for more
details on this data type.

Return Value These functions return the floating-point remainder. If y is 0, the function returns 0.

Compatibility fmod

• ANSI • DOS • OS/2 • U N IX • XEN IX

fmodl

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

See Also ceil, fabs, floor

I * FMOD . C : T h i s p r o g r a m d i s p l a y s a f l o a t i n g - p o i nt rema i n d e r . */

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


#i n c l ude < s td i o . h >
fmod, �di 294

v o i d ma i n ( )
(
I'
doubl e x = - 10 . 0 , y = 3.0, z;

z = fmod ( x , y ) ;
p r i ntfC " T h e rema i nd e r of % . 2 f I % . 2f i s %f\ n " , x , y , z ) ;

Output ,

J
T h e rema i n d r of - 1 0 . 00 I 3 . 00 i s - 1 . 000000
295 fopen

Daer/pl/an Opens a file.

#include <Stdio.h>

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

filename Path name of file


mode 'IYpe of access pennitted

Remalks The fopen function opens the file specified by filename. The character string mode speci­
fies the type of access requested for the file, as follows:

Description
" r" Opens for reading. If the file does not exist or cannot be
found, the fopen call will fail.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed
" a" Opens for writing at the end of the file (appending); creates
the file first if it doesn't exist.
" r+" Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
" a+" Opens for reading and appending; creates the file first if it
doesn't exist.

When a file is opened with the " a " or " a+ " access type, all write operations occur at the
end of the file. Although the file pointer can be repositioned using fseek or rewind, the file
pointer is always moved back to the end of the file before any write operation is carried
out. Thus, existing data cannot be overwritten.
When the " r+" , " w+" , or " a+ " access type is specified, both reading and writing are al­
lowed (the file is said to be open for "update"). However, when you switch between read­
ing and writing, there must be an intervening fsetpos, fseek, or rewind operation. The
current position can be specified for the fsetpos or fseek operation, if desired.
fopen 296

In addition to the values listed above, one of the following characters can be included in
mode to specify the translation mode for newline characters:

Mode Meaning

t Open in text (translated) mode. In this mode, carriage-return­


line-feed (CR-LF) combinations are translated into single line
feeds (LF) on input and LF characters are translated to CR-LF
combinations on output. Also, CTRL+Z is interpreted as an end­
of-file character on input. In files opened for reading or for
reading/writing, fopen checks for a CTRL+Z at the end of the
file and removes it, if possible. This is done because using the
fseek and ftell functions to move within a file that ends with a
CTRL+Z may cause fseek to behave improperly near the end of
the file.
b Open in binary (untranslated) mode; the above translations are
suppressed.

lf t or b is not given in mode, the translation mode is defined by the default-mode variable
_fmode. If t or b is prefixed to the argument, the function will fail and return NULL.
See Section 2. 7, "Input and Output," for a discussion of text and binary modes.

Return Value The fopen function returns a pointer to the open file. A null pointer value indicates an
error.

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

Note that the t option is not part of the ANSI standard for fopen; it is a Microsoft exten­
sion and should not be used where ANSI portability is desired.

See Also fclose, fcloseall, fdopen, ferror, fileno, freopen, open, setmode

1
I
I * FO P EN . C : h i s p r o g r a m opens f i l e s n a med " d a t a " a n d " d a t a 2 " . I t u s e s
* f c l o s e to c l o s e " d a t a " a nd fcl o s ea l l to c l o s e a l l rema i n i ng f i l e s .
*I

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


297 fopen

F I L E * s t ream , * s t ream2 :

v o i d ma i n C l
{
i nt n umc l o s ed ;

I * Open f o r r e a d ( w i l l fa i l i f ' d a t a ' does not e x i s t ) * /


i f ( ( s t re a m = fopen C " d a t a • , • r • l l == N U L L l
p r i n t f ( " T h e fi l e ' d a t a ' w a s not opened \ n " l :
el se
p r i n t f ( " T h e fi l e ' d a t a ' wa s o p e n ed \ n " l :

I * Open f o r w r i t e * /
i f ( C s t r eam2 = fope n C " d a t a 2 " , • w+ • l l == N U L L
p r i n t f ( " T h e fi l e ' d a t a 2 ' wa s n o t ope n ed \ n� l :
el se
p r i n t f ( " T h e f i l e ' d a t a 2 ' w a s opened \ n " l :

I * C l o s e s t re a m * /
i f ( fcl o s e C s t ream l
p r i n t f C " T h e fi l e ' d a t a ' wa s not c l o s ed \ n " l :

I * Al l o t h e r f i l e s a re c l osed : * /
n u mc l o s e d = f c l o s ea l l ( l :
p r i n t f ( " N umb e r of f i l e s c l o s e d by f c l o s e a l l : % u \ n " , n umc l o s ed l :

T h e f i l e ' d a t a ' wa s o p ened


T h e f i l e ' d a t a 2 ' w a s o p e n ed
N umbe r of f i l e s c l o s e d by f c l o s ea l l : 1

(
FP_OFF, FP_SEG 298

Description Get or set a far-pointer offset (FP OFF) or a far-pointer segment (FP SEG)
_ _
.

#include <dos.h>

unsigned FP_OFF( void _far *address );


unsigned FP_SEG( void _far *address );

address Far pointer to memory address

Remarks The FP OFF and FP SEG macros can be used to set or get the offset and segment, respec­
_
_

tively, of the far pointer at address.

Return Value The FP OFF macro returns an offset. The FP SEG macro returns a segment address.
_
_

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

Examp� �--����-
1 * F P _S EG . C : T h i s p r o g r a m u s e s F P_S EG a n d F P_O F F t o obta i n
* t h e s e g e n t a n d offset of t h e l ong p o i n t e r p .
* /'

lli n c l ude < d o s . h>


lli n c l ude < a l l oc . h>
lli n c l ude < s t d i o . h>

v o i d ma i n ( )
{
v o i d _fa r *p ;

f.
u n s i g n ed i nt s e g_v a l ;
u n s i g n e d i n t off_v a l ;

p = _fma l l oc ( 100 ); I * P o i n t s p o i n t e r a t s omet h i ng * /

s e g_v a l F P -S E G C p ) ; I * Gets a d d r e s s p o i nted to */


off_v a l FP OFF( p ) ;

pri ntf ( Segment i s % . 4X ; Offset i s % . 4 X \ n " , s e g_v a l , off_v a l ) ;

.
299 FP_OFF, FP_SEG

Output

Segment i s 00C7 ; O f f s e t i s 00 1 6
_Ipreset 300

Description Resets the floating-point package.

#include <float.h>

void _fpreset( void );

Remarks The _fpreset function reinitializes the floating-point-math package. This function is usu­
ally used in conjunction with signal, system, or the exec or spawn functions.
If a program traps floating-point error signals (SIGFPE) with signal, it can safely recover
from floating-point errors by invoking _fpreset and using longjmp.
In DOS versions prior to 3.0, a child process executed by exec, spawn, or system may
affect the floating-point state of the parent process if an 8087 or 80287 coprocessor is
used. If you are using either coprocessor, the following precautions are recommended:

• The exec, spawn, and system functions should not be called during the evaluation of a
floating-point expression.
• The _fpreset function should be called after these routines if there is a possibility of
the child process performing any floating-point operations.

Return Value None.

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

See Also exec functions, signal, spawn functions


I * F P R E S ET . C : T h i s p r o g r a m u s e s s i g n a l to s e t up a r o u t i n e f o r h a n d l i n g
* fl o a t i n g poi nt e r rors .

Il
*'


#i n c l ude < s td i o . h>
#i n c l ude < s i gna l . h>
#i n c l ude < s �t j mp . h >
#i n c l ude <s dl i b . h>
#i n c l ude < f l o a t . h>
#i n c l u d e <ma t h . h >
#i n c l ude <s ri ng . h>
301 _Ipreset

j mp_b u f ma r k ; I * Ad d r e s s for l o n g j ump t o j ump t o * /


i nt fperr ; / * Gl oba l e r r o r numb e r * /

v o i d f p h a n d l e r ( i n t s i g , i n t n um ) ; / * P r ototy p e s * /
voi d fpchec k ( vo i d ) ;

v o i d ma i n ( )
[.
d o ub l e n l , n 2 , r ;
i n t j mp ret ;

I * Set u p f l oa t i n g p o i nt e r r o r h a n d l er . * /
i f ( s i g n a l ( S I G F P E , fph a nd l e r ) � S I G_ E R R
(
f p r i n t f ( s t d e r r , " Co u l dn ' t s e t S I G F P E \ n " ) ;
a b o rt ( ) ;

I * S a v e s t a c k env i ronment for r e t u r n i n c a s e of e r r o r . F i rst t i me


* t h ro u g h , j mpret i s 0 , s o t r ue c o n d i t i o n a l i s executed . I f a n
* e r r o r o c c u r s , j mp ret w i l l b e s et t o - 1 a n d fa l s e con d i t i on a l
* w i l l b e executed .
*/
j mp r et = s et j mp ( ma r k ) ;
i f ( j mp ret == 0 )
(
p r i n t f ( " T e s t f o r i n v a l i d o p e ra t i on - • ) ;
p r i n t f ( " en t e r two n umbe r s : • );
s c a n f ( " % l f % l f " , & n l , &n2 ) ;

r = n l I n2 ;
I * T h i s won ' t b e r e a c hed i f e r ror o c c u r s . * /
p r i n t f ( " \ n \ n %4 . 3 g I %4 . 3 g %4 . 3 g \ n " , n l , n2 , r ) ;
=

r = n l * n2 ;
I * T h i s won ' t be r e a c h e d i f e r r o r o c c u r s . * /
p r i n t f ( " \ n \ n %4 . 3g * %4 . 3 g %4 . 3 g \ n " , n l , n2 , r ) ;
=

)
el se
fpc h e c k ( ) ;
I
I
_ !preset !
voiI* dHanIfphand
dles Ier(GFPEi nt( floating poinumnt ) error) i nterrupt. */
302

1
I

sig, i n t
**/* Sethand1l1·lobale r. for outsi de check since we don' t want to do I/O in the
fperrI* I n i=1tialize
num; floati ng-poi nt package. */
_fI*presReste 1 r();e calling environment and jump back to setjmp. Return
*Ilongj* so·mtp(l[atmark,setjmp will return false for condi ti onal test . -1

;•i dcharfpchec,Clfp tr[30];


-1 ) ;
l

switch(cas]fperrFPE_I NVALI D :
strcpy C fpstr " I nvali d number"
>

case�tr;::reak;c:py:VERFLC fpsOtW:r, "Overflow"


I >:

case�trrFPEecak;pyUNDERFL
( fpstOr,W: " Underflow "
l;

cas� FPE_ZERODI V I D E:
>:

defa'f����reak;�: :::��: ::::�:·,::.: ::· ,:: ,, error"


pri) ntf( •Error %d: %s\n", fperr, fpstr
l ;

> :

TesErrort for131:invD' vlii ddeoperby azerotion - enter two numbers: 0


Output

5
303 fprinff

DBBcripllan Prints formatted data to a stream.

#include <Stdio.Ii>

int fprintf( FILE *stream, const char *format [ , argument ] ... ) ;

stream Pointer to FILE structure

format Format-control string


argument Optional arguments

Remades The fprintf function formats and prints a series of characters and values to the output
stream. Each argument (if any) is converted and output according to the corresponding
format specification informal.

Theformat argument has the same form and function that it does for the printf function;
see the Remarks section for the printf function for more information onformat and
argument.

Retum Value The fprintf function returns the number of characters printed, or a negative value in the
case of an output error.

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

See Also cprintf, fscanf, printf, sprintf

I*
*
*
pritheFPRIFPRInDOStNNTF.TF.thTYPEOCemU: TThistooncothemthemaprnfilod.scrgraemenaenusmeedusis nfprintf
FPRIg thNTF.e syOtoUsTtfore. mImtfunctiatthenvariousodin stopladai yntsvoka eand
#i#i nnclude
clude <stdi<process.o . h> h>
*
*I
I
fprintf 1

*str a m ;
304

voi di nmaint i = 10 ;
F I LE

doublcharchar e s[]cfp===' \1.n';" t5;his is string";


fprifprisfpt rriennanmttt =((( fopen(
strstrstreaeeaammm ,,, " f""" %printf.
s%%d\n",f\%c",n ", os,fpi ut•,);c );
a

"w" >:

fclose
system str" typeeamfpri); ntf. out• ); > ;

this11.0500000is a string
Output
305 fputc, fputchar

Description Write a character to a stream (fputc) or to stdout (fputchar).

#include <Stdio.h>

int fputc( int c, FILE *stream );


int fputchar( int c );

c Character to be written
stream Pointer to FILE structure

Remarks The fputc function writes the single character c to the output stream at the current posi­
tion. The fputchar function is equivalent to fputc(c, stdout).
The fputc and fputchar routines are similar to putc and putchar, but are_functions rather
than macros.

Return Value The fputc and fputchar functions return the character written. A return value of EOF indi­
cates an error.

Compatibility fputc

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

fputchar

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

See Also fgetc, fgetchar, putc, putchar

/*
arraFPUTC.y toC : Thistdout.s program uses fputc and fputchar to send a character
#i nclude <stdi o . h>
*
*I
voi dcharmai nst() ptrl[ ] "This i s a test of fputc!! \ n";
306

charcharI* Prin*p;st�ptrline2 [ ] to= str"Thiseami susia ntestg fputc.of fputchar!! \ n";


(

pwh=i le(str C trl;*p ! = ' \0 ') fputc( *C p++),*/stdout ! =


/*=;strrinjpC *trpline2 ;! = t' o\0s' t) reamfputcharC
using fputch*C p+a+)r. */) ! =
&& > EOF )

pwhile( && EO F

ThisThis ii ss a Jt stst ooff fputc!


I

fputcha ! !
Output


a I
r

I I

II

(
307 fputs

DBBt:l'/pllan Writes a string to a s�.

#Include <Stdio.II>

\
int fputs( const char *string, FILE *stream );

string String to be output


stream Pointer to FILE structure

The fputs function copies string to the output stream at the current position. The tenninat­
ing nuil character ('\0') is not copied.
Rsmalks

Rstum Va/us The fputs function returns a nonnegative value if it is successful. If an error occurs, it re­
tums .EOF.

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

S11Alla fgets, gets, puts

I * FPUTS . C : T h i s p r o g r a m u s e s fputs to w r i t e a s i n g l e l i n e to t h e
s td o u t s t ream .
*I
*

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

v o i d ma i n ( )
{
f p u t s ( " H e l l o w o r l d from fputs . \ n " , s td o u t ) ;

Output

H e l l o w o r l d f rom fputs .
tread 308

Description Reads data from a stream.

#include <Stdio.h>

size t fread( void *buffer, size t size, size t count, FILE *stream );
- - -

buffer Storage location for data


size Item size in bytes
count Maximum number of items to be read
stream Pointer to FILE structure

Remarks The fread function reads up to count items of size bytes from the input stream and stores
them in buffer. The file pointer associated with stream (if there is one) is increased by the
number of bytes actually read.
If the given stream is opened in text mode, carriage-return-line-feed pairs are replaced
with single line-feed characters. The replacement has no effect on the file pointer or the re­
turn value.
The file-pointer position is indeterminate if an error occurs. The value of a partially read
item cannot be determined.

Return Value The fread function returns the number of full items actually read, which may be less than
count if an error occurs or if the file end is encountered before reaching coullt.
The feof or ferror function should be used to distinguish a read error from an end-of-file
condition. If size or coullt is 0, fread returns 0 and the buffer contents are unchanged.

Campatlblllty • ANSI • DOS • OS/2 • U N IX • XEN IX

See Also fwrite, read

I * F R EA D . C : T h i s p r o g r a m o p e n s a f i l e n a me d F R EA D . O UT a n d w r i t e s 25
* c h a r a c t e s t o t h e f i l e . I t t h e n t r i e s t o o p e n F R EAD . O U T a n d
* r e a d i n 5 c h a r a c t e r s . I f t h e a t t empt s u c c e e d s , t h e p r o g r a m
* d i s p l a y s t h e n u mb e r o f a c t u a l i t ems r e a d .
*I
809 tread

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

v o i d ma i n ( )
(
F I L E * s t r ea m ;
c h a r l i s t [ 30 ] ;
i nt i , numrea d , numw r i t t e n ;

I * Open f i l e i n text mod e : * I


i f ( ( s t re a m = fopen C " f rea d . out • , • w+t • > > ! = N U L L >
(
for C i = 0 ; i < 2 5 ; i ++ )
l i s t [ i ] "' ' z ' - i ;
I * W r i t e 2 5 c h a r a c t e r s to s t ream */
n umw r i t t e n m fwr i t e ( l i st , s i z e o f ( c h a r ) , 2 5 , s t re a m ) ;
p r i n t f C " W rote %d i tems \ n " , numw r i tten ) ;
f c l o s e C s t ream > :
}
el se
p r i n t f ( " P robl em open i ng t h e f i l e \ n " > :

i f ( ( s t re a m = fope n C " f r e a d . out • , • r+t • ) ) I = N U L L )


(
I * Att empt to rea d i n 25 c h a r a c t e r s * /
n umr e a d = frea d C l i s t , s i zeof ( c h a r ) , 2 5 , s t ream > :
p r i n t f ( " N umbe r o f i t ems r e a d = Zd\ n " , numread > :
p r i n t f C " C o n t e n t s of buffer = % . 2 5 s \ n " , l i s t > :
f c l o s e C s t ream > :
}
el se
p r i n t f C " Wa s n o t a b l e to open t h e fi l e\ n " > :

Output

W r o t e 2 5 i t ems
N umber of i t ems r e a d = 2 5
C o n t e n t s o f b u f f e r = zyxwv u t s rqponml kj i hgfedcb

r
free Fun lions 310

Dsscrlptlan Deallocate a memory block.

#include <Stdlib.h> For ANSI compatibility (free only}


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

void free( void •memblock );


void _bfree( _segment seg, void _based( void ) •memblock );
void _ffree( void _far •memblock ) ;
void _nfree( void _near •memblock ) ;

memblock Allocated memory block


seg Based-heap segment selector

Remalks The free family of functions deallocates a memory block. The argument memblock points
to a memory block previously allocated through a call to calloc, malloc, or realloc. The
number of bytes freed is the number of bytes specified when the block was allocated (or
reallocated, in the case of realloc}. After the call, the freed block is available for
allocation.
The seg argument specifies the based heap containing the memory block to be freed by the
_bfree function.
Attempting to free an invalid pointer may affect subsequent allocation and cause errors.
An invalid pointer is one not allocated with the appropriate call.
The following restrictions apply to use of the free, _bfree , _ffree, and _nfree functions:

Blocks allocated with: Should be freed with:

calloc, malloc, realloc free


_bcalloc, _bmalloc, _brealloc _bfree
_fcalloc, _fmalloc, _frealloc _ffree
_ncalloc, _nmalloc, _nrealloc nfree

A NULL pointer argument is ignored.


In large data models (compact-, large-, and huge-model programs}, free maps to _ffree. In
small data models (tiny-, small-, and medium-model programs}, free maps to _nfree.
311 free Functions

The various free functions deallocate a memory block in the segments shown in the list
below:
Function Data Segment

free Depends on data model of program


_bfree Based heap specified by seg value
_ffree Far heap (outside default data segment)
_nfree Near heap (inside default data segment)

RBtum Value None.

Compat/blllly free

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

_bfree, _ffree, _nfree

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

See Also calloc functions. malloc functions. realloc functions

/ * M A L LOC . C : Th i s p r o g r a m a l l o c a t e s memo ry w i t h ma l l oc , t h e n frees


* the memo ry w i t h f re e .
*I

#i n c l u d e < s t d l i b . h> I * D e f i n i t i on o f _MA X_PATH * /


#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 >
I
free Funf ons

oi dcharmain(>*st[li ng;
312


i

striif(/* Alloc teg space_MAXfor_aPATHpath>: name */


nprintstrig � mallocC
elsefree(pri nstt iCC ng"I" Mnemsuorffiy cspi eantce memor
== NULL )
y avail
allocated fora bl e
path\n" >:
na m e\n" );
pri ntfC Memory freed \n" );
l :

MeMemormoryy spacfree4! allocated for path name


Output

f.

I
313 _freect

Description Returns the amount of memory available for memory allocation.

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

unsigned int _freect( size_t size );

size Item size in bytes

Rematks The _freect function tells you how much memory is available for dynamic memory alloca­
tion in the near heap. It does so by returning the approximate number of times your pro­
gram can call _nmalloc (or malloc in small data models) to allocate an item size bytes
long in the near heap (default data segment).

Return Value The _freect function returns the number of calls as an unsigned integer.

Compal/bll/ly D ANSI • DOS • OS/2 D UNIX D XENIX

See Also calloc functions, _expand functions, malloc functions, _memavl, _msize functions,
realloc functions

I*
*
FREEintegersCT.inCt: egersinThistheprogra aulmtdeterdatthea msegmen
defand checks i nsespacehotwagai. muchThenn, freeusii t nalloca
spacet is
es
g _freect. s availabl
p ace for e for
#i#ivoinnclude <malloc. h>
* 1 , 000

clude <stdi o . h >


*I

( dintmaii:n ()
I*
pri nFtf(i rst_fr"Irnetegers
poreect(t onsizeof( ( athepproxifrei mnetate)space:avai l able on heap: %u\n\n ",
*/

I* Allocai tesispai zeof(<ce forint++i) ) integers:


for<mallocC= 0; 1000 ;
1000

>:
) ) >:

*/
_lreect

nallocati
pripriI* nnReportf(tf( _1tt·•]�l agaifternrtegers */availablei nontegers:heap: \%u\n " n);\n",
on ( theapproxinfrgemespate)space:
314

eect( si zeof( i nt ) ) ) ;
a c e for
1 000

IAfterntegersalloca( ap��ringoxi msate)pace availabl


Output

e on heap:
I ntegers < apfroxi mate) foravai l ablei nontegers:heap:
15212

1000
1 4084
315 treapen

Description Reassigns a file pointer.

#include <Stdio.h>

FILE lllfreopen( const char *filename, const char *mode, FILE *stream );

filename Path name of new file


mode 'fype of access pennitted
stream Pointer to FILE structure

Remarks The freopen function closes the file currently associated with stream and reassigns stream
to the file specified by filename. The freopen function is typically used to redirect the pre­
opened files stdio, stdout, and stderr to files specified by the user. The new file associ­
ated with stream is opened with mode, which is a character string specifying the type of
access requested for the file, as follows:

Description
" r" Opens for reading. If the file does not exist or cannot be
found, the freopen call fails.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed.
"a" Opens for writing at the end of the file (appending); creates
the file first if it does not exist.
" r+ " Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
"a+ " Opens for reading and appending; creates the file first if it
does not exist.

Use the " w" and " w+ " types with care, as they can destroy existing files.
When a file is opened with the "a" or "a+ " access type, all write operations take place at
the end of the file. Although the file pointer can be repositioned using fseek or rewind, the
file pointer is always moved back to the end of the file before any write operation is car­
ried out. Thus, existing data cannot be overwritten.
!reopen 316

When the " r+" , " w+" , or " a+ " access type is specified, both reading and writing are al­
lowed (the file is said to be open for "update"). However, when you switch between read­
ing and writing, there must be an intervening fsetpos, fseek, or rewind operation. The
current position can be specified for the fsetpos or fseek operation, if desired.
In addition to the values listed above, one of the following characters may be included in
the mode string to specify the translation mode for newlines.

Mode Meaning

t Open in text (translated) mode; carriage-return-line-feed


(CR-LF) combinations are translated into single line-feed
(LF) characters on input; LF characters are translated to CR­
LF combinations on output. Also, CTRL+Z is interpreted as an
end-of-file character on input. In files opened for reading, or
writing and reading, the run-time library checks for a CTRL+Z
at the end of the file and removes it, if possible. This is done
because using the fseek and ftell functions to move within a
file may cause fseek to behave improperly near the end of the
file.

b Open in binary (untranslated) mode; the above translations are


suppressed.

If t or b is not given in the mode string, the translation mode is defined by the default
mode variable _fmode.
See Section 2.7, "Input and Output," for a discussion of text and binary modes.

Retum Va/ue The freopen function returns a pointer to the newly opened file. If an error occurs, the orig­
inal file is closed and the function returns a NULL pointer value.

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

The t option is not part of the ANSI standard for freopen; it is a Microsoft extension that
should not be used where ANSI portability is desired.

See A/BO fclose, fcloseall, fdopen, rdeno, fopen, open, setmode

*
*/
named Thi s prograand wrim rteesassignsa linesttodauthatx to thefi l efile.
/ * FREO P E N . , :
F R O P E N . OUT
!reopen

#i#include
nclude <s<stdlitdio.bh. >h>
317

*str
voi d mai n ()
FI LE e a m ;
strif(I* eRaestrmassi=eamgfrn==eopen(" stdaux" f" rtoeopen." freoopen.ut", o"wut":", s*/tdaux
{

elsefprfprii nntf(tf( stdout, " error on freopen\n " );


l ;

NULL )

fprfcl oi ntf(se( strstrstdout,eeamam );, ""Ts uccessfull


his will goy rtoeassithegfilened\n "' fr);eopen. out' \ n" );
system( " type freopen. out" );
Thisuccessfull
s will goy toreassithegnedfi l e ' freopen. out'
Output
I
frexp, t/frxpl 318

I
Dsscrlptlon
I Get the mantissa and exponent of a floating-point number.

#include <math.h>

double frexp( double x, int *expptr );


long double frexpl( long double x, int *expptr );

x Floating-point value

expptr Pointer to stored integer exponent

Remarks The frexp and frexpl functions break down the floating-point value (x) into a mantissa (m)
and an exponent (n), such that the absolute value of m is greater than or equal to 0.5 and
less than 1 .0, and x = m *2 ". The integer exponent n is stored at the location pointed to by
expptr.
The frexpl function is the 80-bit counterpart and uses an 80-bit, l 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 These functions return the mantissa. If x is 0, the function returns 0 for both the mantissa
and the exponent. There is no error return.

Compatibility I frexp

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

frexpl

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

SBB A/so ldexp functions, modf

and n. !This program calculates frexp( &n ), then displ ays y


!
Example �--1��������������������������������
I* FREXP . C : 16 . 4 ,

{I/ii nnclcludeude
*
*I I
frexp, frexpl

voi( ddoublmai ne ()x,


319

intx n; y;

y =
pri nfrtf(exp(" frexpCx, &n%f,); &n ) %f, n %d\n", x, n
= 16 . 4 ;

= = y, >:

frexpC &n
Output

1 6 . 400000 , > = n
0 . 5 1 2 500 , = 5
tscanf 320

Oescr/pl/on Reads formatted data from a stream.

#include <Stdio.h>

int fscanf( FILE *stream, const char *format [, argument ] ••• )

stream Pointer to FILE structure

format Format-control string

argument Optional arguments

Remarks The fscanf function reads data from the current position of stream into the locations given
by argument (if any). Each argument must be a pointer to a variable with a type that corre­
sponds to a type specifier informal. The format controls the interpretation of the input
fields and has the same form and function as theformat argument for the scanf function;
see scanf for a description offormat.

Return Value The fscanf function returns the number of fields that were successfully converted and as­
signed. The return value does not include fields that were read but not assigned.
The return value is EOF for an error or end-of-file on stream before the first conversion. A
return value of 0 means that no fields were assigned.

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

See Also cscanf, fprintf, scanf, sscanf

his prtoograrmeawrid thetes vaforri mousatteddatdataa backto fra omfile.the filI t e .


then uses rscanf
/ * FSCAN F . C : T

#i nclude <stdio. h>


*
*I
i
fscanf

LEvoi d mai*strne()am;
321

( floatong fp;;
FI

charcharint rs[c;esul81];t ;
1 1

strif( prieasmtnr=tf(eamfopen(=="TheNULLfile" fscanf.) fscoanutf.",out"w+"was not opened\n" );


else( fpri ntf( stream , " %s %ld %f%c", " a -stri ng",
l;

;
fsI*I*eSetek(Readpoistrdataneteramback, to0L, befrSEEKgomi n_ningfiSEl Te : of*I fi l e : */
65000 , 3 . 14 1 5 9 , ' x ' )

fsfscanf
fsfscccanf(aannf(f( strstrstrstream,eeeaaammm ,,, """"%%%%f",cs",l d ".&c&fps&l) ); ););
l;

Ipri* Output
nntf(tf( """ %%%das\f\n",l dtn\an",",reasfpd) :););; */
C

priprintf(
•,

prifcl notf(se( str" %c\enam", c


l;
1

l;

a-stri ng
Output

6 5000
3 . 1 4 1 590
x
lseek 322

Oest:rlpllon Moves the file pointer to a specified location.

#include <Stdio.h>

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

stream Pointer to FILE structure


offset Number of bytes from origin
origin Initial position

Remadts The fseek function moves the file pointer (if any) associated with stream to a new location
that is offset bytes from origin. The next operation on the stream takes place at the new lo­
cation. On a stream open for update, the next operation can be either a read or a write.
The argument origin must be one of the following constants defined in STDIO.ff:

Origin Definition

SEEK_CUR Current position of file pointer

SEEK_END End of file

SEEK_SET Beginning of file

The fseek function can be used to reposition the pointer anywhere in a file. The pointer
can also be positioned beyond the end of the file. However, an attempt to position the
pointer in front of the beginning of the file causes an error.

The fseek function clears the end-of-file indicator and negates the effect of any prior
ungetc calls against stream.

1/0 operation, not by where the next write would occur. If no I(O operation has yet oc­
When a file is opened for appending data, the current file position is determined by the last

curred on a file opened for appending, the file position is the start of the file.
For streams opened in text mode, fseek has limited use because carriage-return-line-feed
translations can cause fseek to produce unexpected results. The only fseek operations
guaranteed to work on streams opened in text mode are the following:

• Seeking with an offset of 0 relative to any of the origin values


• Seeking from the beginning of the file with an offset value returned from a call to ftell
323 fseek

Return Value If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable
of seeking, the return value is undefined.

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

SBB A/so ftell, lseek, rewind

1***/movesFSEEK. theC : Thispoi nprogra ter tomtheopensfile'thes fibegil enniFSEEK.ng. OUT and
Exampm ������-

include <stdi
voi( dFILEmai n*strea() m :
# o . h >
chi natr reine[sult:81J:
stri f ( epriasmtnr-etf(amfopenC=="The file" fseek.fsoeut",ek. out"w+"was >not: opened\n" >:
1

else( fpri ntf( stream , "The fseek begi ns here:


NU L L )

resi f( perrultresul=o r(tfse") ekCFseekstr"Tfaiehisaml ed", is the>: SEEKfile_SE' Tfs):eek. out'. \n " >:

else( pri ntf( " Fi le poi nter is set to mi ddle of first line. \n " >:
23L ,

fgets(
pri n tf( li"%ne,s", 80,linestr);eam >:
)
fcl oseC. stream l:

is the fileis set' fseek.to miodut'.dle of first li ne.


ThisFile pointer
Output
fsetpos 324

DBScr/pt/on Sets the stream-position indicator.

#include <Stdio.h>

int fsetpos( FILE *stream, const fpos_t *pos ) ;

stream Target stream


pos Position-indicator storage

Remarks The fsetpos function sets the file-position indicator for stream to the value of pos, which is
obtained in a prior call to fgetpos against stream.
The function clears the end-of-file indicator and undoes any effects of the ungetc function
on stream. After calling fsetpos, the next operation on stream may be either input or
output.

Return Value If successful, the fsetpos function returns 0. On failure, the function returns a nonzero
value and sets ermo to one of the following manifest constants (defined in ERRNO.H):

Constant Meaning

EBADF The object that stream points to is not a valid file handle, or
the file is not accessible.
EINVAL An invalid stream value was passed.

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

SIB Also fgetpos

* d i fferent h o c a t i o n s .
/ * FGETPOS . C : 1 T h i s p r o g r a m opens a f i l e a n d rea d s byt e s a t s e v e r a l

*I


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

voi( d mai n ()*stream ;


325

fposcharint _t buffer[
FI LE
pos;val; 20];
if(elsepri( strntf(eam"=Trofopen(uble opening " fgetpos.file\n"c ", " rb);" )) )
== N U L L

friI*fe( perrad(Readfgetpos(obuffer,
some dastrtsieazameof(an, d&posthcharen ) check),! = 010th, estrposieamt i);on. */
el( sfread(e r( buffer, " fgetpos error" ); >

pri ntf( "10 bytessizeof(at bytechar%ld:), %.101, 0s\strne",ampos,); buffer );


posIi *f ( perrSetfse14tpos(oa0;r(new" fposisetpos
=
tstreami o, n&posand rea) ! =d mor0 )e data. */
error" );
fread(pri nbuffer, tf( " 1 0 bsiyteszeof(atcharbyte ),%l d10: , %.st10res\amn " );, pos, buffer );
fclose< stream >:

1100 bbyytestes atat bbyytete 11400:: This p*


Output

.C:
FI LE
_fsopen 326

D1scr/pllon Opens a stream with file sharing.

#include <Stdio.h>
#include <Share.h> sliflag constants

FILE "'_fsopen( const char "'filename, const char •mode, int shflag );

filename File name to open


mode 'fype of access permitted
shflag 'fype of sharing allowed

R1matlcs The _fsopen function opens the file specified byfilename as a stream and prepares the
file for subsequent shared reading or writing, as defined by the mode and shflag
arguments.
The character string mode specifies the type of access requested for the file, as follows:

Description

" r" Opens for reading. If the file does not exist or cannot be
found, the _fsopen call will fail.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed.
"a" Opens for writing at the end of the file (appending); creates
the file first if it does not exist.
" r+ " Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
"a+ " Opens for reading and appending; creates the file first if it
does not exist.

Use the " w" and " w+ " types with care, as they can destroy existing files.
When a file is opened with the " a" or " a+ " access type, all write operations occur at the
end of the file. Although the file pointer can be repositioned using fseek or rewind, the file
pointer is always moved back to the end of the file before any write operation is carried
out. Thus, existing data cannot be overwritten.
327 _lsopen

When the " r+ " , " w+ " , or "a+ " access type is specified, both reading and writing are al­
lowed (the file is said to be open for "update"). However, when switching between reading
and writing, there must be an intervening fsetpos1 fseek, or rewind operation. The current
position can be specified for the fsetpos or fseek operation, if desired.

In addition to the values listed above, one of the following characters can be included in
mode to specify the translation mode for newlines:

Mode Meaning

t Open in text (translated) mode. In this mode, carriage-retum­


line-feed (CR-LF) combinations are translated into single line
feeds (LF) on input and LF characters are translated to CR-LF
combinations on output. Also, CIRL+Z is interpreted as an end­
of-file character on input. In files opened for reading or read­
ing/writing, _fsopen checks for a CIRL+Z at the end of the file
and removes it, if possible. This is done because using the
fseek and ftell functions to move within a file that ends with a
CIRL+Z may cause fseek to behave improperly near the end of
·

the file.
b Open in binary (untranslated) mode; the above translations are
suppressed.

If t or b is not given in mode, the translation mode is defined by the default-mode variable
_fmode. If t or b is prefixed to the argument, the function will fail and will return NULL.
See Section 2. 7, "Input and Output," for a discussion of text and binary modes.
The argument shflag is a constant expression consisting of one of the following manifest
constants, defined in SHARE.H. If SHARE.COM -or SHARE.EXE for some versions of
DOS- is not installed, DOS ignores the sharing mode. (See your system documentation
for detailed information about sharing modes.)

Constant Meaning
SH_COMPAT Sets compatibility mode (not available in OS/2)
SH_DENYNO Permits read and write access
SH_DENYRD Denies read access to file
SH_DENYRW Denies read and write access to file
SH_DENYWR Denies write access to file

The _fsopen function should be used oniy under OS/2 and DOS versions 3.0 and later.
Under earlier versions of DOS, the shflag argument is ignored.
_lsapen 328

Retum Value The _fsopen function returns a pointer to the stream. A NULL pointer value indicates an
error.

Campatl/Jll/ly D ANSI • DOS • OS/2 D UNIX D XENIX

S11 Alsa fclose, fcloseall, fdopen, ferror, tileno, fopen, freopen, open, setmode, sopen

I***IfcloseFSOPEN. toC : Thiclossepr"doata•gram opensand fcloseallfiles namtoedclose"data•allandremai"data2".n i ng fiI tl es.uses


I/lFILEii nnclcludeude*strea<st<shm iroe .. hh>>
voi( dFILEmai n*str() am ;
I*I** Openthat on tputone elsefile wrifortwries ttoi ntheg. Usifi nl ge _fsopen
while we alloarewwris ustingto toensurei t .
if(( fpri( strnetfm( strea_fsompen(, " No• ooneutfile",else i n"wt•,the SnetH_wDENYWR
ork can )) wri t NULL
e •
• t o this fi l e un t il w e ar e done. \ n"
= I=

fclose str e a m );
sIy*stNoewm( ot· rypeers outfile" can wri te );to the file while we read i t .
>:

*/

I
No one else n the network can write to this fi l e until we are done.
Output
329 fstat

D•criptlan Gets infonnation about an open file.

#include <Sys\types.h>
#include <Sys\stat.h>

int fstat( int handle, struct stat *buffer );

handle Handle of open file


buffer Pointer to structure to store results

Remarks The fstat function obtains infonnation about the open file associated with handle and
stores it in the structure pointed to by buffer. The structure, whose type stat is defined in
SYS\C>TAT.H, contains the following fields:

Field Value

st_atime Time of last modification of file (same as st-mtime and


st_ctime).
st_ctime Time of last modification of file (same as st-atime and
st_mtime).
st_dev Either the drive number of the disk containing the file, or
handle in the case of a device (same as st_rdev).
st_mode Bit mask for file-mode infonnation. The S IFCHR bit is set if
handle refers to a device. The S IFREG bit is set if handle re­
fers to an ordinary file. The readtwrite bits are set according to
the file's pennission mode. (S_IFCHR and other constants are
defined in SYS\ STAT.H.)
st_mtime Time of last modification of file (same as st-atime and
st_ctime).
st_nlink Always I .
st_rdev Either the drive number of the disk containing the file, or
handle in the case of a device (same as st_dev).

st_size Size of the file in bytes.

If handle refers to a device, the size and time fields in the stat structure are not
meaningful.
!stat 330

Retum Value The fstat function returns the value 0 if the file-status infonnation is obtained. A return
value of -1 indicates an error; in this case, ermo is set to EBADF, indicating an invalid file
handle.

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

In OS/2, the st_dev field does not contain meaningful infonnation. In fact, it is set to zero.
OS/2 provides no way to recover the host drive from just the open file handle.

Sn AllD access, chmod, fllelength, stat

1***InaFSTmAT.ed CFt. AT.ThisOUTprogra. m uses fstat to report the si ze of a fil e


Examp� �-+-������---

I#iI#incl//ii nclude
nclude
n#include l
<i
<f 1 0 . h
cludeude <s<t<sli ms\ts\stat.
c ntl >
e. yh. >pes.h> h>h>
#i#i#i nnnclude
clude
clude <stdi
<s
<stri dli o
n b.
g. h
. >
hh>>
� oi dstructmain()s!�at buf:
charif(int fh,C buffer[
f h
resul]t : "A line to output":
open( " f stat. out", O _ CRE A T O _WRONL Y O _TRUNC >> >
exi t ( >:
=

wri/* tGete( datah, buffassociated


1
er, strlenCwi thbuffer" f h": ) >:
I I == -1

resul t fstatC fh, &buf >: */


lstat

ielsef ( priChresencktf(ul tif " Bstatisti c s are vali d :


331

I*
!= 0 )
ad file handle\n " */

pripripri nnntfCtfCtf( "File""TDirimevemodifie


sizenumberd %ld\n", buf. s t _ si z e
>:

%d\n",
%s", buf.
cti m e( s t _ dev
&buf. s t _
>:

ati m e
close( fh
>:
) >:
}
>:

DriTiFilemevemodisinuzmefberied Thu Jun


Output

16
0
15 2 1 : 38 : 46 1 989
Itel/ 332

Description Gets the current position of a file pointer.

#include <Stdio.h>

long ftell( FILE *stream );

stream Target FILE structure

Remarks The ftell function gets the current position of the file pointer (if any) associated with
stream. The position is expressed as an offset relative to the beginning of the stream.
Note that when a file is opened for appending data, the current file position is detennined
by the last 1/0 operation, not by where the next write would occur. For example, if a file is
opened for an append and the last operation was a read, the file position is the point where
the next read operation would start, not where the next write would start. (When a file is
opened for appending, the file position is moved to end-of-file before any write operation.)
If no 1/0 operation has yet occurred on a file opened for appending, the file position is the
beginning of the file.

Return Value The ftell function returns the current file position. The value returned by ftell may not re­
flect the physical byte offset for streams opened in text mode, since text mode causes
carriage-return-line-feed translation. Use ftell in conjunction with the fseek function to re­
turn to file locations correctly. On error, the function returns -IL and errno is set to one of
the following constants, defined in ERRNO.H:

Constant Description

EBADF Bad file number. The stream argument is not a valid file­
handle value or does not refer to an open file.
EINVAL Invalid argument. An invalid stream argument was passed to
the function.

On devices incapable of seeking (such as tenninals and printers), or when stream does not
refer to an open file, the return value is undefined.
333 Itel/

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

See Also fgetpos, fseek, lseek, tell

I*** positriFTELL.etsionCto: Thisofreadthepr10ofile0gracharampoiopenscters.ntera andfileI t displthenanmedausyessFTthisftellELL. Cpotoforsi tdeteri oren.adimni gneanthed


*I#i nclude <stdio. h>
FILEvoi d mai*stream;n ()
I

charlongif{ ( posislist[1tretamion;0=0J;fopen( " ftel l . c ", " rb " ) ) ! = NULL


I

frI*I*eMovead(Get posilist,thetpointer eof( bycharreread:adi), */ng100,data:st r*/eam


sii onzafter
posifclose(t i onstr"P=oesiftell(amt i o);n after
streamtr);yi ng to read 100 bytes: %ld\n", posi tion
>:

printf( >:

Posi t i on after tryi ng to read 100 bytes: 100


Output
ftime 334

Description Gets the current time.

/
#include <Sys\types.h>
#include <Sys\timeb.h>

void ftime( struct timeb *timeptr );

timeptr Pointer to structure defined in SYS\TIMEB.H

Remarks The ftime function gets the current time and stores it in the structure pointed to by timeptr.
The timeb structure is defined in SYS\TIMEB.H. It contains four fields (dstflag, millitm,
time, and timezone), which have the following values:

Field Value

dstflag Nonzero if daylight saving time is currently in effect for the


local time zone. (See tzset for an explanation of how daylight
saving time is determined.)

millitm Fraction of a second in milliseconds. The last digit is always 0


since millitm is incremented to the nearest one-hundredth of a
second.

time Time in seconds since 00:00:00 Greenwich mean time,


January 1 , 1970.

timezone Difference in minutes, moving westward, between Greenwich


mean time and local time. The value of timezone is set from
the value of the global variable timezone (see tzset).

Return Value The ftime function gives values to the fields in the structure pointed to by timeptr. It does
not return a value.

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


335 !time

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

I * FT I M E . C : T h i s p r o g r a m u s e s ft i me to obta i n t h e c u r re n t t i me
* a n d t h en s t o re s t h i s t i me i n t i mebuffer .
*I

#i n c l u d e < s td i o . h>
#i n c l u d e < sy s \ t i meb . h >
#i n c l u d e <t i me . h>

v o i d ma i n ( )
(

s t r u c t t i meb t i meb u ff e r ;
c h a r * t i mel i n e ;

ft i me C & t i mebuffer ) ;
t i me l i ne = c t i me ( & C t i mebuffe r . t i me > > :

p r i n t f ( " T h e t i me i s % . 1 9 s . % h u %s " ,
t i mel i n e , t i mebuffer . mi l l i tm , &ti mel i n e [ 20 ] > :

Output

T h e t i me i s T h u J u n 1 5 2 1 : 40 : 34 . 87 0 1 989
tu I/pat, 336

Description Makes an absolute path name from a relative path name.

#include <stdlib.h>

char *_fullpath( char *buffer, const char *pathname, size_t max/en ) ;

buffer Full path-name buffer

pathname Relative path name

max/en Length of the buffer pointed to by buffer

Remarks The _fullpath routine converts the partial path stored in pathname to a fully qualified path
that is stored in buffer. Unlike _makepath, the _fullpath routine can be used with .\ and \ ••

in the path.

If the length of the fully qualified path is greater than the value of max/en, then NULL is
returned; otherwise, the address of buffer is returned.

If the buffer is NULL, _fullpath will allocate a buffer of MAX_PATH size and the
max/en argument is ignored.

If the pathname argument specifies a disk drive, the current directory of this drive is com­
bined with the path. If the drive is not valid, _full path returns NULL.

Return Valu 1I The _fullpath function returns a pointer to the buffer containing the absolute path
(buffer). If there is an error, _fullpath returns NULL.

Compatibili t 0 ANSI • DOS • OS/2 0 U N IX 0 XENIX

I
I
See A/so ' getcwd, _getdcwd, _makepath, _splitpath

I * F U L L P A W H . C : T h i s p r o g r a m d em o n s t r a t e s h o w _f u l l p a t h c r e a t e s a f u l l
* p a t h f�om a p a r t i a l p a t h .
*I i

i< c on i o . h >
#i ncl ude �stdi o . h>
1fo i n c l u d e
#i ncl ude 1< s t d l i b . h >
#i n c l ude :< d i rect . h>
I
�fuHpath

charvoi d maifull[n ()_MAX_PATH], part [_MAX_PATH];


337

( while(
gets(priif( nparbreak:
tf(part [" 0tEnJ ter== 0part i a l path or ENTER to qui t :
1
(
• >:
>:

if(else_fullpri ntf(path("Fufull,ll pathpa is:rt , _MAX%s\n",_PATHfull) ! = NULL


>

pri ntf( " I nvali d pa th\n" >:


>:

Enterpaparpartitht ii aas ll: pathpathC: \ oror ENTER


FullEnter
llutput

to qui t :
FullFullEnterpapathpartht is:ii asl: C:paP: t\\hi norcludeENTER
ENTER to
to qui
qui . t
t •:
: p: \i n clude
Enter
FullEnterpathpartipartiis:aa ll C:pathpath\ LIorBorREF\ENTER
fENTERullpath.toto quiquictt :: full path. c
fwrite 338

Description Writes data to a stream.

#include <Stdio.h>

size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

buffer Pointer to data to be written


size Item size in bytes
count Maximum number of items to be written
stream Pointer to FILE structure

Remarks The fwrite function writes up to count items, of length size each, from buffer to the output
stream. The file pointer associated with stream (if there is one) is incremented by the num­
ber of bytes actually written.
If stream is opened in text mode, each carriage return is replaced with a carriage-return­
line-feed pair. The replacement has no effect on the return value.

Return Value The fwrite function returns the number of full items actually written, which may be less
than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be
determined.

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

See Also fread, write

FREreadAD.cinft¢rsC i Thistocharaprthecoters.grafile.m opensIfI tthethaeafilenttetriesmnamed


chara to FRE
openA D.
F O
R UT
E A and
D. O U T wri
andt es
display the number of actual i temsptread.succeeds, the program
I* 25

f
*
* 25

#i nclude <stdi o . h>


*
*I I
339 !write

v o i d ma i n ( )
(
F I L E * s t r ea m ;
c h a r l i s t [ 30 J ;
i nt i , numrea d , n umw r i t t e n ;

I * Open f i l e i n text mod e : * /


i f ( ( s t re a m = fopen ( " f read . out " , " w+t " l l ! = N U L L l
(
f o r ( i = 0 ; i < 2 5 ; i ++ )
l i st [ i ]
= 'z' - i ;
I * W r i t e 2 5 c h a ra c t e r s to s t ream * /
numw r i t t e n = fw r i t e ( l i s t , s i zeof ( c h a r ) , 2 5 , s t ream ) ;
p r i n t f ( " W rote %d i tems \ n " , n umw r i tten ) ;
f c l o s e ( s t ream ) ;

el se
p r i n t f ( " P ro b l em open i n g t h e f i l e \ n " ) ;

i f ( ( s t re a m = fope n ( " f re a d . out " , • r+t • ) ) ! = N U L L )


(
I * Att empt t o r e a d i n 25 c h a r a c t e r s * /
n umread = f r e a d ( l i s t , s i zeof ( c h a r ) , 2 5 , s t ream ) ;
p r i n t f ( " N umber of i t ems r e a d = % d \ n " , numread ) ;
p r i n t f ( " C o n t e n t s of buffer = % . 2 5 s \ n " , l i s t ) ;
f c l o s e ( s t re a m ) ;

el se
p r i n t f ( " Wa s n o t a b l e t o open t h e f i l e \ n " ) ;

Output

Wrote 2 5 i t ems
Numb e r of i t ems read = 2 5
C o n t e n t s of b u f f e r = zyxwv u t s rqponml kj i hgfedcb
gcvt 340

Description Converts a floating-point value to a string, which it stores in a buffer.

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

char *gcvt( double value, int digits, char *buffer );

value Value to be converted


digits Number of significant digits stored
buffer Storage location for result

Remarks The gcvt function converts a floating-point value to a character string and stores the string
in buffer. The buffer should be large enough to accommodate the converted value plus a
terminating null character ('\0'), which is appended automatically. There is no provision
for overflow. ·

The gcvt function attempts to produce digits significant digits in decimal format. If this is
not possible, it produces digits significant digits in exponential format. Trailing zeros may
be suppressed in the conversion.

Return Value / The gcvt function returns a pointer to the string of digits. There is no error return.

lib/II,
I

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

I
I
See A/so atof, atoi, atol, ecvt, fcvt

GCV
I
Exampre ��
T . C J This progra m converts -3. 1 4 15e5 to i t s stri n g repres e ntati o n.
�������������������������������

#i#i nnclude
clude 1stdli
{stdi ob. h. >h>
I* */
i

I
341 gcvt

v o i d ma i n ( )
(
c h a r b u f f e r [ 50 l :
doubl e source - - 3 . 141 5e5 :

g c v t C s o u r c e , 7 , buffe r > :
p r i n t f C " s o u r c e : %f b u f fe r : ' % s ' \ n " , s o u r c e , buffe r ) ;

Output

s o u rc e : - 3 1 4 1 50 . 000000 buffe r : ' - 3 1 4 1 50 . '


342

Description Gets the current active page number.

#include <graph.h>

short _far _getactivepage( void );

Remarks The _getactivepage function returns the number of the current active page.

Return Value The function returns the number of the current active page. All hardware combinations sup­
port at least one page (page number 0). In OS(l, only page 0 is valid.

Compatibility D ANSI • DOS D OS/2 D U NIX D XENIX

See Also _getactivepage. _getvideocontig, _getvisualpage, _grstatus, setactivepage, _

_setvideomode, _setvisualpage

I* PAGE._geC i activepa lustratesgevi_gedeotpavisualge functipage o_setactivepa


ns includ i ng:ge _setvisualpage
#i#i#include
nnclude <c l nio. h >
*

<g aph. h >h>


*I

clude f <s fr dli b .


voi dshormaitn (> 1dvpag' e, oldapage, page, row , col, li ne;
[
{

char_gstreutvictdluf[ioconfig(
tj
deoconfi
80]; g&vcvc;);
if(ol dapagvc.exi umvi _getactivepa
d);eopages < 4ge();) Fa il for OS/2 or monochrome.
ol dvpagIcursor(_getvisual
_displa
C 1
=
=
_GCURSORpagOe();FF );
/* */

I
_getacttvepage

I * D r a w a r rows i n d i fferent p l a c e o n e a c h p a g e . * /
fo r ( p a g e = 1 ; p a g e < 4 ; p a g e++ >
(
_s et a c t i v epa ge ( p a g e > :
_s ettextpos i t i on ( 1 2 , 1 6 * pa ge > :
_ou t t ex t ( " > > > > >> > > " > :

w h i l e ( ! kb h i t ( ) )
I * Cyc l e t h ro u g h p a g e s 1 t o 3 to s h ow mo v i n g i ma g e . * I
fo r ( p a g e= 1 ; p a g e < 4 ; p a g e++
_s et v i s u a l pa g e ( p a g e > :
getch C > :

I * Re s t o r e o r i g i n a l p a g e ( n o rma l l y 0 ) to r e s t o r e s c reen . * I
_s e t a c t i v epa g e ( o l d a p a ge > :
_s e t v i s u a l p a g e ( o l d v p a g e > :
_d i s pl a y c u rs o r ( _GC U RSORON > :
getarcin 344

Description Detennines the endpoints in viewport coordinates of the most recently drawn arc or pie.

#include <graph.h>

short _far _getarcinfo( struct xycoord _far *start, struct xycoord _far *end,
struct xycoord _far *fillpoint );

start Starting point of arc

end Ending point of arc

fillpoint Point at which pie fill will begin

Rematits The _getarcinfo function detennines the endpoints in viewport coordinates of the most re­
cently drawn arc or pie.

If successful, the _getarcinfo function updates the start and end xycoord structures to con­
tain the endpoints (in viewport coordinates) of the arc drawn by the most recent call to one
of the _arc or _pie functions.

In addition,fillpoint specifies a point from which a pie can be filled. This is useful for
filling a pie in a color different from the border color. After a call to _getarcinfo, change
colors using the _setcolor function. Use the color, along with the coordinates infillpoi11t,
as arguments for the _floodfill function.

Retum Value The _getarcinfo function returns a nonzero value if successful. If neither the _arc nor the
_pie function has been successfully called since the last time the screen was cleared or a
new graphics mode or viewport was selected, the _getarcinfo function returns 0.

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

See Also _arc functions, _floodfill, _getvideoconfig, _grstatus, _pie functions

Example See the example for _arc.


345 _getbkcalar

Description Gets the current background color.

#include <graph.h>

long _far _getbkcolor( void );

Remarks The _getbkcolor function returns the current background color. The default i s 0.

In a color text mode such as _TEXTC80, _setbkcolor accepts, and _getbkcolor returns, a
color index. For example, _setbkcolor(2L) sets the background color to color index 2. The
actual color displayed depends on the palette mapping for color index 2. The default for
color index 2 is green in a color text mode.
In a color graphics mode such as _ERESCOLOR, _setbkcolor accepts and _getbkcolor re­
turns a color value (as used in _remappalette). The value for the simplest background
colors is given by the manifest constants defined in the GRAPH.ff include file. For ex­
ample, _setbkcolor( _GREEN) sets the background color in a graphics mod<? to green.
These manifest constants are provided as a convenience in defining and manipulating the
most common colors. In general, the actual range of colors is much greater.

In most cases, whenever an argument is long, it refers to a color value, and whenever it is
short, it refers to a color index. The two exceptions are _setbkcolor and _getbkcolor, de­
scribed above. For a more complete discussion of colors, see _remappalette.

Retum Value The function returns the current background color value. There is no error return.

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

See Also _remappalette, _setbkcolor

Example See the example for _getcolor.


getc, getc ar � 346

Description Reads a character from a stream (getc), or gets a character from stdio (getchar).

#include <Stdio.h>

int getc( FILE *stream );


int getchar( void );

stream Current stream

Remarks The getc macro reads a single character from the stream position and increments the as­
sociated file pointer (if there is one) to point to the next character. The getchar macro is
identical to getc(stdin).
The getc and getchar routines are similar to fgetc and fgetchar, respectively, but are mac­
ros rather than functions.

Return Value The getc and getchar macros return the character read. A return value of EOF indicates an
error or end-of-file condition. Use ferror or feof to determine whether an error or end-of­
file occurred.

Compatibility getc

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

getchar

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

See Also fgetc, fgetchar, getch, getche, putc, putchar, ungetc

!
I * G ETC . C : 1 h i s p r o g r a m u s e s get c h a r to r e a d a s i n g l e l i n e of i n put
* f r om s t d n , pl a c e s t h i s i n put i n buffe r , t h en t e rmi n a t e s t h e
* s t ri n g b f o r e p r i n t i n g i t t o t h e s c reen .
*I

#i n c l u d e < s t d i o . h >
347 getc, getchar

v o i d ma i n < >
(
c h a r buffe r [ 8 1 ] ;
i nt i , c h ;

p r i ntf ( " E n t e r a l i n e : • ) ;

I * Read i n s i n g l e l i n e f r om " s t d i n " : * /


fo r < i = 0 ; - C i < 80 ) && ( ( c h = g e t c h a r ( ) ) ! = EO F > && C c h ! = ' \ n ' ) ; i ++ >
buffe r [ i ] = c h ;

I * Termi n a t e s t r i n g w i t h n ul l c h a r a c t e r : * /
buffer [ i ] = ' \0 ' ;
p r i n t f ( " % s \ n " , buffe r ) ;

Output

E n t e r a l i n e : T h i s i s a l i n e of text .
T h i s i s a l i n e of text .
gstch, gs r:he 348

D11t:t/ptlon Get a character from the console without echo (getch) or with echo (getche).

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

int getch( void ) ;


int getche( void );

Rematlts The getch function reads a single character from the console without echoing. The getche
function reads a single character from the console and echoes the character read. Neither
function can be used to read CTRL+C.

When reading a function key or cursor-moving key, the getch and getche functions must
be called twice; the first call returns 0 or OxEO, and the second call returns the actual key
code.

Retum Value The getch function returns the character read. There is no error return.

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

See A/so cgets, getchar, ungetch

I * G ETCH . C : T h i s p ro g r a m r e a d s c h a r a c t e r s from t h e keyboa rd u n t i l i t


* re c e i v e s a ' Y ' o r ' y ' .
*I

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


#i n c l ude < c f y p e . h >
349 getch, getche

v o i d ma i n ( }
(
i nt ch ;

c p u t s ( " Type ' Y ' w h e n f i n i s h ed typi n g keys : • > :


do
(
c h = getc h < > :
c h = touppe r ( c h > :
whi l e( ch ! = ' Y ' > :

put c h ( c h > :
putch ( ' \ r ' > : / * C a r r i a g e ret u r n * /
putch ( ' \ n ' } : / * Li ne feed */

Output

Type ' Y ' w h e n fi n i s h ed typ i n g keys : Y


_getcolo � 350

OBScr/ption Gets the current color.

#include <graph.h>

short _far _getcolor( void );

Remarks The _getcolor function returns the current graphics color index. The default is the highest
legal value of the current palette.

Return Value The _getcolor function returns the current color index.

Compatibility I D ANSI • DOS D OS/2 D UNIX D XEN IX

See Also setcolor

I*
*
OUTTX_sett_gettT . C�r xtcolor
f
i
xtcolThisoexar m_setbk ple illustra
_getbk ccolorolor tes_s_gettextposi
textettextposioutputtt ii functi
oonn _outons:text
#include <cbni o . h >
*

#include I
<s�di o . h >>
*I

#include
charvoi d maibuffen r <g
1 [ 80 ] ;
aph. h
I
q

:d,i nrik,goli ddnfgd,bgd;aloldpos;foreground,


shortstrlonguSactveblb�nccoor oldfgd; bac kground, and text posi t i on.
I


!
/* */

ololol dddSavebgdfgdpos j,ori_gettextcolor(l;


g_getbki n alcolor(); foreground, background, and text posi t i on.
_clears r_gettextposi een( _GCLEARSCREti on();EN );
I* */

j

361 _getco/or

I * Fi r s t t i me n o b l i n k , s e c o n d t i me b l i n k i n g . * /
f o r ( b l i n k = 0 ; b l i n k <= 1 6 ; b l i n k += 1 6 )
{
/ * Loop t h ro u g h 8 b a c kground c o l o r s . * /
fo r < b g d = 0 ; b g d < 8 ; bgd++ )
{
_s e t b k c o l o r ( bgd > :
_s ettextpos i t i on ( C s h o rt ) bgd + ( ( b l i n k I 1 6 ) * 9 ) + 3 , 1 )�
_s ettextcol o r < 7 > :
s p r i n t f ( bu f fe r , " Ba c k : %d Fore : " , bgd ) ;
_o utt ext < b u f f e r ) ;

I * Loop t h r o u g h 1 6 f o r e g r o u n d col o r s . * /
fo r ( f g d = 0 ; f g d < 1 6 ; fgd++ )
{
_s ettextc o l o r ( fgd + b l i n k ) ;
s p r i n t f ( buffe r , • %2d " , fgd + b l i n k ) ;
_ou t t ext ( buffe r ) ;

)
getch < > :

I * Res t o r e o r i g i n a l foreg round , b a c k g r o u n d , a nd text pos i t i on . * /


_s ettextc o l o r < o l d fgd > :
_s e t b k c o l o r ( o l dbgd > :
_c l ea r s c reen ( _GC L EARSC R E E N ) ;
_s ettextpos i t i on ( o l d p o s . row , o l d p o s . c o l > :
1I
_getcurre tposition Functions 352

i
Description I Get the current position and return it as a structure.

I #include <graph.h>

struct xycoord _far _getcurrentposition( void );


struct _wxycoord _far _getcurrentposition_w( void );

Remarks The _getcurrentposition functions return the coordinates of the current graphics output
position. The _getcurrentposition function returns the position as an xycoord structure,
defined in GRAPH.H.

The xycoord structure contains the following elements:

Element Description

short xcoord x coordinate

short ycoord y coordinate

The _getcurrentposition_w function returns the position as an _wxycoord structure, de­


fined in GRAPH.H.
The _wxycoord structure contains the following elements:

Element Description

double wx window x coordinate

double wy window y coordinate

The current position can be changed by the _lineto, _moveto, and _outgtext functions.
The default position, set by _setvideomode, _setvideomoderows, or _setviewport, is the
center of the viewport.
Only graphics output starts at the current position; these functions do not affect text output,
which begins at the current text position. (See _settextposition for more information.)

Return Value The _getcurrentposition function returns the coordinates of the current graphics output
position. There is no error return.
358 _getcurrentpasitian Functions

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

See Also _grstatus, _lineto functions, _moveto functions, _outgtext

I * GCU RPOS . C : T h i s p r o g r a m s e t s a r a n d om c u r r e n t l oc a t i on , t he n g e t s t h a t
* l o c a t i on w i t h _g et c. u r rentpos i t i on .
*I

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


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

char buffe r [ 2 5 5 ] ;

v o i d ma i n ( )
(
s t ruct v i d e o c o n f i g v c ;
s t ruct xy c o o r d pos i t i on ;

I * Fi n d a v a l i d g r a p h i c s mode . * /
i f ( l _s e t v i d e omod e C _MAX RESMODE
exi t C 1 ) ;
_g etv i d e o c o n f i g C & v c l ;

I * Move t o r a n d om l o c a t i on a n d report t h a t l oc a t i on . * /
_mo v et o ( r a n d ( ) % v c . n umx p i x e l s , r a n d ( ) % v c . n umy p i x e l s l ;
pos i t i on = _get c u r re n t p o s i t i on C l ;
s p r i n t f C buffe r , • x = %d , y = %d " , pos i t i on . xcoord , po s i t i on . y c o o r d l ;
_s ettextpos i t i on C l , 1 l ;
_ou t t ex t C buffer l ;

getch C l ;
_s e t v i d eomod e C _D E FAU LTMO D E l ;
· getcwd 354

DBBt:rlpllon Gets the current working directory.

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

char *getcwd( char *buffer, int max/en );

buffer Storage location for path name


max/en Maximum length of path name

Remadts The getcwd function gets the full path name of the current working directory and stores it
at buffer. The integer argument max/en specifies the maximum length for the path name.
An error occurs if the length of the path name (including the terminating null character)
exceeds max/en.
The buffer argument can be NULL; a buffer of at least size max/en (more only if neces­
sary) will automatically be allocated, using malloc, to store the path name. This buffer can
later be freed by calling free and passing it the getcwd return value (a pointer to the allo­
cated buffer).

Retum Value The getcwd function returns a pointer to buffer. A NULL return value indicates an error,
and errno is set to one of the following values:

Value Meaning

ENOMEM Insufficient memory to allocate max/en bytes (when a NULL


argument is given as biif.fer)
ERANGE Path name longer than max/en characters

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

See A/so chdir, mkdir, rmdir

f
I * T h i s p r o r a m pl a c e s t h e n a me of t h e c u r re n t d i rect o ry i n t h e b u f f e r
* a r ray , t e n d i s p l a y s t h e n a me of t h e c u r re n t d i r e c t o ry on t h e s c reen .
* Spec i fy i g a l en g t h o f MAX O I R l ea v e s room for t h e l on g e s t l eg a l
_ _

* d i rec t o r n a me .
*I

I
355 getcwd

#i n c l ude < d i rect . h>


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

v o i d ma i n ( )
(
c h a r buffer [_MAX_D I R J ;

I * Get t h e c u r rent w o r k i n g d i r e c t o ry : * /
i f ( get cwd C b u ffe r , _MAX_D I R ) == NULL )
p e r ro r C • g etcwd e r r o r • > :
el se
pri ntfC " Ss \ n " , buffer > :

Output

C : \ LI BREF
I
_getdcwd asB

DBScrlpllon Gets full path name of current working directory, including disk drive.

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

char *_getdcwd( int drive, char *buffer, int max/en );

drive Disk drive


buffer Storage location for path name
max/en Maximum length of path name

Rematks The _getdcwd function gets the full path name of the current working directory, Including
disk drive specification, and stores it at buffer. The argument max/en specifies the maxi­
mum length for the path name. An error occurs if the length of the path name (including
the terminating null character) exceeds max/en.
The drive argument specifies the drive (0 = default drive, l=A, 2=B, etc.). The buffer argu­
ment can be NULL; a buffer of at least size max/en (more only if necessary) will automat­
ically be allocated, using malloc, to store the path name. This buffer can later be freed by
calling free and passing it the _getdcwd returri value (a pointer to the allocated buffer).

Return Value The _getdcwd function returns buffer. A NULL return value indicates an error, and errno
is set to one of the following values:

Value Meaning

ENOMEM Insufficient memory to allocate max/en bytes (when a NULL


argument is given as buffer)
ERANGE Path name longer than max/en characters

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

i
See A/BO chdir, getcwd, _getdrive, mkdir, rmdir

I
!
Exampm ��I�������������������������������
I * G E T D R I V E . C i l l u s t r a t e � d r i v e func t i o n s i n c l u d i n g :
* _g � t d r i ve _c hd r i v e _g etd cwd
*I
as1 _getdcwd

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


#i n c l ude <coni o . h>
#i n c l ude < d i rect . h >
#i n c l ude <stdl i b . h>

v o i d ma i n ( )
(
i nt ch , dri ve , curdri ve ;
s t a t i c c h a r pa th [_MAX_PATH J ;

I * S a v e c u r re n t d r i v e . * /
c u rd r i v e = _getd r i v e C l ;

p r i n t f ( " A v a i l a bl e d r i v e s a re : \ n " l ;

I * I f we c a n swi t c h to t h e d r i v e , i t exi s t s . * /
fo r e d r i v e = 1 ; d r i v e <= 26 ; d r i v e++ )
i f ( ! _c h d r i v e C d r i v e l l
p r i ntf ( " %c : • , d r i ve + ' A ' 1 l ;
-

whi l e( 1 l
(
p r i n t f ( " \ nType d r i v e l et t e r t o c h e c k o r ESC to q u i t : " l ;
c h = getc h C l ;
i f( ch = 27 l
b r ea k ;
i f ( i sa l pha C c h l l
put c h ( c h l ;
i f ( _g etd cwd C touppe r C c h l - ' A ' + 1 , p a t h , _MAX_PATH l ! = N U L L
p r i n t f ( " \ n C u r re n t d i r e c t o ry o n t h a t d r i v e i s % s \ n " , p a t h l ;

/ * Re s t o r e o r i g i na l d r i v e . T h i s i s on l y n e c e s s a ry f o r DOS . U n d e r O S / 2
* t h e c u r r ent d r i v e of t h e c a l l i n g p r o c e s s i s a l ways r e s t o red .
*I
_c h d r i v e C c u rd r i v e l ;
pri ntf( " \ n " ) ;
I
_getdcw� 358

Output


Av a i l a bl e d r i v e s a re :
A: B: C:
Ty pe d r i v e l et t e r t o c h e c k o r ESC t o q u i t : q
Ty pe d r i v e l et t e r to c h e c k or ESC to q u i t : a
C u r rent d i r c t o ry on t h a t d r i v e i s A : \

Ty pe d r i v e l et t e r t o c h e c k o r E S C t o q u i t : c
C u r rent d i r c t o ry o n t h a t d r i v e i s C : \ L I B R E F

Ty pe d r i v e � etter t o check or ESC t o q u i t :

I
I
359 _getdrive

Description Gets the current disk drive.

#include <direct.h>

int _getdrive( void );

Remarks The _getdrive function returns the current working drive ( l =A, 2=B, etc.).

Return Value The return value is stated above. There is no error return.

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

See Also _chdrive, _dos_getdrive, _dos_setdrive, _getcwd, _getdcwd

Example See the example for _getdcwd.


getenv 360

Dest:rlptlan Gets a value from the environment table.

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

char *getenv( const char *varname );

varname Name of environment variable

Rematts The getenv function searches the list of environment variables for an entry corresponding
to varname. Environment variables define the environment in which a process executes.
(For example, the LIB environment variable defines the default search path for libraries to
be linked with a program.) Because the getenv function is case sensitive, the varname vari­
able should match the case of the environment variable.

The getenv function returns a pointer to an entry in the environment table. It is, however,
only safe to retrieve the value of the environment variable using the returned pointer. To
modify the value of an environmental variable, use the putenv function.

The getenv and putenv functions use the copy of the environment contained in the global
variable environ to access the environment. Programs th� use the envp argument to main
and the putenv function may retrieve invalid infonnation. The safest programming prac­
tice is to use getenv and putenv.

Return Value The getenv function returns a pointer to the environment table entry containing the current
string value of varname. The return v alue is NULL if the given variable is not currently
defined.

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

The getenv function operates only on the data structures accessible to the run-time library
and not on the environment "segment" created for a process by DOS or OS/2.

See Also putenv

I * G ET E N V . C : T h i s p r o g r a m u s e s g e t e n v to ret r i eve t h e L I B e n v i ronment


* v a r i a b l e and then uses putenv t o c h a n g e i t t o a n ew v a l u e .
*I

jstdl i b . h>
j s td i o . h >
#i n c l u d e
#i n c l u d e
361 getenv

ma i n ( )
[
c h a r * l i b va r ;

I * Get t h e v a l u e o f t h e L I B e n v i ronment v a r i a b l e . * /
l i bv a r = getenv ( " L I B " ) ;
i f ( l i b va r ! = N U L L )
p r i n t f ( " O r i g i n a l L I B v a r i a b l e i s : % s \ n " , l i b va r ) ;

I * Att empt t o c h a n g e p a t h . N o t e t h a t t h i s o n l y a f f e c t s t h e e n v i ronment


* v a r i a b l e of the c u r r ent p r o c e s s . T h e c omma nd p roc e s s o r ' s e n v i ronment
* i s not c h a n ged .
*I
p u t en v < " L I B=c : \ \ my l i b ; c : \ \ you r l i b " ) ;

I * Get new va l u e . * /
l i bv a r = g e t en v < " L I B " ) ;
i f ( l i bv a r ! = N U L L )
p r i n t f ( " N ew L I B v a r i a b l e i s : % s \ n " , l i b va r ) ;

Output

O r i g i n a l L I B va r i a b l e i s : C : \ L I B
N ew L I B va r i a b l e i s : c : \ my l i b ; c : \ y o u r l i b
362

Dest:rlptlon Gets the current fill mask for some graphics routines.

#include <graph.h>

unsigned char _far * _far _getftllmask( unsigned char _far *mask );

mask Mask array

Remades Some graphics routines (_ellipse, _floodfill, _pie, _polygon, and _rectangle) can fill part
or all of the screen with the current color or background color. The fill mask controls the
pattern used for filling.
The _getfillmask function returns the current fill mask. The mask is an 8-by-8-bit array, in
which each bit represents a pixel. If the bit is 1 , the corresponding pixel is set to the current
color; if the bit is 0, the pixel is left unchanged. The mask is repeated over the entire fill
area. If no fill mask is set, or if mask is NULL, a solid ( unpatterned) fill is performed using
the current color.

Return Value If no mask is set, the function returns NULL.

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

See Also _ellipse functions, _floodfill, _pie functions, _polygon functions, _rectangle functions,
_setfillmask

This progr a m illustra t es _getfill m ask a n d etfill m ask


#i#i#i nnnclude
clude <coni o . h
clude jgraph. h>h>
�s t dli b . >
I * G F I L LM S K . C : _ s . */
363 _getflHmask

v o i d e l l i p s ema s k ( s h o r t x l , s h o rt y l , s h o r t x 2 , s h o r t y 2 , c h a r _fa r *n ewma s k l ;

u n s i gned c h a r ma s k l [ B J { 0x43 , 0x23 , 0 x 7 c , 0xf7 , 0x8a , 0x4d , 0x78 , 0x39 J ;


u n s i gned c h a r ma s k2 [ 8 ] = { 0 x l 8 , 0x a d , 0xc0 , 0 x 7 9 , 0xf6 , 0xc4 , 0x a 8 , 0x23 J ;
c h a r o l dma s k [ 8 ] ;

v o i d ma i n ( )
[
i n t l oop ;

I * F i nd a v a l i d g r a p h i c s mod e . * /
i f ( ! _s et v i d eomod e ( _MAX RESMODE
exi t ( 1 l ;

I * Set f i r s t f i l l ma s k a n d d r a w rect a n g l e . * /
_s e t f i l l ma s k ( ma s k l l ;
_recta n g l e ( _G F I L L I NT E R I O R , 20 , 20 , 100 , 100 l ;
getc h ( l ;

I * C a l l rou t i n e t h a t s a v e s a n d r e s t o res ma s k . * /
e l l i p s ema s k ( 60 , 60 , 1 50 , 1 50 , ma s k 2 ) ;
getc h < l :

I * Ba c k t o o r i g i n a l ma s k . */
_rect a n g l e ( _G F I L L I NT E R I O R , 1 20 , 1 20 , 1 9 0 , 1 9 0 ) ;
getc h ( l ;

_s e t v i d e omod e ( _D E FAU LTMO D E l ;

I * D r a w a n e l l i p s e wi t h a s p e c i f i ed f i l l ma s k . * /
v o i d e l l i p sema s k ( s h o rt x l , s ho r t y l , s h ort x 2 , s h o r t y 2 , c h a r _fa r *n ewma s k l
{
u n s i gned c h a r s a vema s k [ 8 ] ;

_g e t f i l l ma s k ( s a vema s k ) ; I* S a v e ma s k */
_s e t f i l l ma s k ( n ewma s k l ; /* Set n ew ma s k */
_e l l i p s e ( _G F I L L I NT E R I O R , x l , y l , x2 , y 2 l ; /* U s e n ew ma s k */
_s e t f i l l ma s k ( s a vema s k ) ; /* Re s t o r e o r i g i n a l */
_getfonti o ,, I
364

Description Gets the current font characteristics.

#include <graph.h>

short _far _getfontinfo( struct _fontinfo _far *fontbuffer );

fontbuffer Buffer to hold font infonnation

Remarks The _getfontinfo function gets the current font characteristics and stores them in a
_fontinfo structure, defined in GRAPH.ff. ·

The _fontinfo structure contains the following elements:

Element Contents

int type Specifies vector ( 1 ) or bit-mapped (0) font

int ascent Specifies pixel distance from top to baseline

int pixwidth Specifies the character width in pixels; 0 indicates a


proportional font

int pixheight Specifies the character height in pixels

int avgwidth Specifies the average character width in pixels


char filename [81] Specifies the file name, including the path

char facename [32] Specifies the font name

Return Value The _getfontinfo function returns a negative number if a font has not been registered or
loaded.

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

See Also _getgtextextent, _outgtext, _registerfonts, _setfont, _setgtextvector,


_unregisterfonts

Example See the example for _outgtext.


365 _getgtextextent

Description Gets the width in pixels of font-based text.

#include <graph.h>

short _far _getgtextextent( unsigned char _far *text );

text Text to be analyzed

Remarks The _getgtextextent function returns the width in pixels that would be required to print the
text string using _outgtext with the current font.
This function is particularly useful for determining the size of text that uses proportionally
spaced fonts.

Return Value The _getgtextextent function returns the width in pixels. It returns -1 if a font has not
been registered.

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

SBB Alsa _getfontinfo, _outgtext, _registerfonts, _setfont, _unregisterfonts

Example See the example for _outgtext.


366

Description Changes the orientation of font text output.

#include <graph.h>

struct xycoord _far __getgtextvector( void );

Remarks The _getgtextvector function gets the current orientation for font text output. The current
orientation is used in calls to the _outgtext function.

The text-orientation vector, which detennines the direction of font-text rotation on the
screen, is returned in a structure of type xycoord. The xcoord and ycoord members of the
structure describe the vector. The text-rotation options are shown below:

(x, y) Text Orientation

(1 ,0) Horizontal text (default)


(0, 1 ) Rotated 90 degrees counterclockwise
(- 1 ,0) Rotated 1 80 degrees
(0,- 1 ) Rotated 270 degrees counterclockwise

Return Value The _getgtextvector function returns the current text-orientation vector in a structure of
type xycoord.

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

See Also __getgtextextent, __grstatus, _outgtext, _setfont, _setgtextvector


367 _getimage Functions

Description Store images in buffers.

#include <graph.h>

void _far _getimage( short xl, short yl, short x2, short y2, char _huge *image );
void _far _getimage_w( double wxl , double wyl, double wx2, double wy2,
char _huge *image );
void _far _getimage_wxy( struct_wxycoord _far *pwxyl,
struct_wxycoord _far *pwxy2, char _huge *image );

xl , yl Upper-left comer of bounding rectangle


x2, y2 Lower-right comer of bounding rectangle
wxl , wyl Upper-left comer of bounding rectangle
wx2, wy2 Lower-right comer of bounding rectangle
pwxyl Upper-left comer of bounding rectangle
pwxy2 Lower-right comer of bounding rectangle
image Storage buffer for screen image

Remarks The _getimage functions store the screen image defined by a specified bounding rectangle
into the buffer pointed to by image.
The _getimage function defines the bounding rectangle with the view coordinates (xl , y1 )
and (x2, y2).

The _getimage_w function defines the bounding rectangle with the window coordinates
(wxl , wyl) and (wx2, wy2).
The _getimage_wxy function defines the bounding rectangle with the window-coordinate
pairs pwxyl and pwxy2.
The buffer must be large enough to hold the image. You can determine the size by calling
the appropriate _imagesize function at run time, or by using the formula described on the
_imagesize reference page.

Retum Value None. Use _grstatus to check success.

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


_getima e Functions 368

See Also _grstatus, _imagesize functions, _putimage functions

I * G I MA G E . C : T h i s e x a mp l e i l l u s t r a t e s a n i ma t i on rout i n e s i n c l ud i n g :
* _i ma ges i z e _g et i ma g e _p ut i ma g e
*I

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


#i n c l ude <stddef . h>
#i n c l ude < tdl i b . h>
#i n c l u d e < a l l oc . h >
#i n c l ude < raph . h>

);
n };
s ho r t a c t i n [ 5 J = ( _G P S ET , _G P R E S ET , _GX O R , _GO R , _GA N O
c h a r * d e s c i p [ 5 J = ( " P S ET " , " P R E S ET " , " X O R " , "OR " , " AN D

v o i d ex i t f e e ( c h a r _h u g e * b u f f e r ) ;

v o i d ma i n q

t
f'
(
cha r h u g e * b u f fe r ; I * Fa r po i n t e r C w i t h _fma l l o c ) c o u l d be u s ed . * /
l on g ms i z e ;
s hort x , y = 30 ;

i f ( ! _ e t v i deomod e ( _MA X R E SM O D E ) )

��
ex " t ( 1 l ;

I * Mea u r e t h e i ma g e to be d r a wn a n d a l l oc a t e memo ry for i t . * /


i ms i z = ( s i z e_t ) _i ma ge s i z e ( - 1 6 , - 1 6 , + 1 6 , + 1 6 ) ;
buffe r = h a l l oc ( i ms i ze , s i z e o f ( c h a r ) ) ;
i f ( u f f e r == ( c h a r _fa r * ) N U L L )
e it( 1 l ; .
I

T
j
_s e t c o r C 3 ) ;

: : : : : :: :� :
or i ;

r D a e l p n w po s i t i on a n d get a copy of i t . * /
x = 50 ; y += 40 ;
_ l l i p s e ( _G F I L L I NT E R I O R , x - 1 5 , y - 1 5 , x + 1 5 , y + 1 5 ) ;
_ et i ma g e ( x - 1 6 , y - 1 6 , x + 1 6 , y + 1 6 , b u f f e r ) ;
i ( _g r s t a t u s ( ) )
e x i t f re e ( b u f f e r ) ; I * Q u i t on e r ro r *I
aBs _getimage Functions

I * D i s p l a y a c t i on type a n d copy a row of e l l i p s e s w i t h t h a t type . * /


_s ettextpos i t i on ( l , 1 > :
_o u t t ex t ( de s c r i p [ i ] > :
wh i l e ( x < 260 )
(
x += 5 ;
_p ut i ma g e ( x - 1 6 , y - 1 6 , buffe r , a c t i on [ i ] l ;
i f ( _g r s t a t u s ( ) < 0 ) / * I g n o r e wa r n i n g s , q u i t on e r ro r s . * /
ex i t f r e e ( b u f f e r > :
}
ge t c h ( l ;

exi tfree ( buffer ) ;

v o i d e x i t f r e e ( c h a r _h u g e * b u f f e r
(
h f re e C b u f f e r l ;
e x i t ( ! _s et v i d eomod e ( _D E FAU LTMO D E l ) ;
370

1
Description Gets the current line style.

#include <graph.h>

unsigned short _far _getlinestyle( void );

Remarks Some graphics routines (_lineto, _polygon, and _rectangle) output straight lines to the
screen. The type of line can be controlled with the current line-style mask.

The _getlinestyle function returns the current line-style mask. The mask is a 1 6-bit array
in which each bit represents a pixel in the line being drawn. If the bit is l , the correspond­
ing pixel is set to the color of the line (the current color). If the bit is 0, the corresponding
pixel is left unchanged. The mask is repeated over the length of the line. The default mask
is OxFFFF (a solid line).

Return Value i If no mask has been set, _getlinestyle returns the default mask.

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

See Also ! _lineto functions, _polygon functions, _rectangle functions, _setlinestyle,


_setwritemode


I * G L I N EST[Y . C : T h i s p r o g r a m i l l u s t r a t e s _s e t l i n estyl e a n d _get l i n e s tyl e . * /

#i n c l u d e coni o . h>
#i n c l u d e stdl i b . h>
#i n c l u d e g ra p h . h >
I
v o i d z i g z � g ( s h o rt x l , s h o r t y l , s h o r t s i z e ) ;

�oi d ma i n r
I * F i n h a v a l i d g r a p h i c s mode . * /
i f ( ! _� e t v i d eomod e ( _MAX C O L O RM O D E ) )
ex i � ( 1 ) ;

1

I * S e t i l i n e s ty l e a n d d ra w r e c t a ng l e . * /
_s e t l i e s tyl e ( 0x4d ) ;
_recta g l e ( _G B O RD E R , 1 0 , 1 0 , 60 , 60 ) ;
getch C) :
871 _getlinestyle

I * D r a w f i g u re w i t h funct i on t h a t c h a nges a nd r e s t o r e s l i n e s t y l e . * /
z i g z a g ( 100 , 100 , 90 > :
getc h ( ) ;

I * O r i g i n a l s ty l e r e u s e d . *I
_recta n g l e ( _GBORD E R , 1 9 0 , 1 90 , 130 , 130 > :
getch C > :

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

I * D r a w box w i t h c h a n g i n g l i n e styl es . Res t o re o r i g i n a l styl e . *I


v o i d z i gz a g ( s h o rt x l , s h ort y l , s h o r t s i z e >
(
s h o rt x , y , o l d c o l o r :
u n s i gned s h o rt o l d s ty l e :
u n s i gned s h o r t s ty l e [ l 6 J = 0x000 1 , 0x0003 , 0x000 7 , 0x000f ,
0x00 l f , 0x003f , 0x007 f , 0x00ff ,
0x0 l f f , 0x03ff , 0x07ff , 0x0fff ,
0xl fff , 0x3fff , 0x 7 fff , 0xffff J :

o l d c o l o r = _getcol o r < > :


o l d s tyl e = _get l i n e s ty l e < > : I * S a v e o l d l i n e styl e . *I
fo r ( x = 3 , y = 3 ; x < s i z e ; x += 3 , y += 3 )
(
_s etcol o r ( x % 1 6 > :
_s et l i n e s ty l e ( s ty l e [ x % 1 6 ] > : I * Set a n d u s e n ew l i n e s ty l e s * /
_recta n g l e ( _GBO RD E R , x l - x , y l - y , x l + x , y l + y > :
)
_s e t l i n e s t y l e ( o l d s ty l e > : / * Restore o l d l i n e sty l e . *I
_s etcol o r ( o l d c o l o r > :
372

Description Gets physical coordinates.

#include <graph.h>

struct xycoord _far _getphyscoord( short x, short y ) ;

x, y View coordinates to translate

Remarks The _getphyscoord function translates the view coordinates (x, y) to physical coordinates
and returns them in an xycoord structure, defined in GRAPH.H.
The xycoord structure contains the following elements:

Element Description
short xcoord x coordinate
short ycoord y coordinate
i
I
Return Value : None.

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

I
I
!
See Also _getviewcoord functions, _grstatus, _setvieworg, _setviewport

Example See the example for _setwindow.


373 gstpid

Dat:l/pllan Gets the process identification.

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

int getpid( void );

RemalkB The getpid function returns the process ID, an integer that uniquely identifies the calling
process.

Return Value The getpid function returns the process ID. There is no error return.

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

S1111 Alsa mktemp

I * G ET P I D . C : T h i s p r o g r a m u s e s getpi d t o obta i n t h e p r o c e s s I D a n d
* then pri nts the I D .
*I

#i ncl ude <stdi o . h>


#i n c l u d e < p r o c e s s . h >

v o i d ma i n ( )
(
I * I f run f rom DOS , s h ow s d i fferent I D f o r DOS t h a n for DOS s h el l .
* I f execed o r s p a wned , s h ows I D o f pa rent .
*I
p r i n t f ( " \ n P ro c e s s i d of pa rent : % d \ n " , g e t p i d ( ) ) ;

Output

P ro c e s s i d o f p a rent : 828
_gstplxsl runctlons
I
374

,,_,,... Get pixel values.

I #include <graph.h>

short _far _getpixel( short x, short y ) ;


short _far _getpixel_w( double wx, double wy ) ;

xy
, Pixel position

wx, wy Pixel position

Remarks The functions in the _getpixel family return the pixel value (a color index) at a specified
location. The _getpixel function uses the view coordinate (x, y) The _getpixel_w function
.

uses the window coordinate (wx, wy). The range of possible pixel values is detennined by
the current video mode. The color translation of pixel values is detennined by the current
palette.

Return Value If successful, the function returns the color index. If the function fails (for example, the
point lies outside the clipping region, or the program is in a text mode), it returns -1 .

Compal/blllty D ANSI • DOS D OS/2 D UNIX 0 XEN IX

See Also _getvideoconfig, _grstatus, _remapallpalette, _remappalette, _selectpalette,


_setpixel functions, _setvideomode

1
ExampM ��������������������������������
I * G P I X E L . Ci: T h i s p r o g r a m a s s i g n s d i f f e r e n t c o l o r s to r a n d oml y

l
!
* s e l e c t e d p i x el s .
*I

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


#i n c l ude < t d l i b . h >
#i n c l u d e < r a p h . h >

v o i d ma i n ( )
i
�fI
s ho r t x a r , y v a r ;
s t r u c t i d eocon f i g v c ;

I
375 _getpixel Functions

I * Fi n d a v a l i d g r a p h i c s mod e . * I
i f ( ! _s et v i d eomod e ( _MA X C O L O RMODE ) )
exi t ( 1 l :
_g e t v i d e o c o n f i g ( & v c > :

I * D r a w f i l l ed e l l i p s e t o t u r n on c e rt a i n p i x e l s . * /
_el l i ps e ( _G F I L L I NT E R I O R , vc . numx p i xel s I 6 , vc . numy p i x e l s I 6 ,
vc . numx p i xel s I 6 * 5 , v c . n umyp i xel s I 6 * 5 ) ;

I * D ra w r a n d om pi x e l s i n r a n d om c o l o r s . . • */
w h il e ( ! kb h i t ( ) l
(
I * . . . b u t on l y i f t h ey a re a l r e a dy on ( i n s i d e t h e e l l i p s e ) . * /
x v a r = r a n d ( ) % · v c . n umx p i x e l s ;
y v a r = r a nd ( ) % v c . n umy p i x e l s ;
i f ( _g e t p i x e l ( x v a r , y v a r ) ! = 0
(
_s e t c o l o r C r a n d ( ) % 1 6 > :
_s e t p i x e l ( x v a r , y v a r > :

getch C l ; / * T h row away t h e key s t ro k e . */


_s e t v i d e omod e ( _D E FAU LTMO D E l ;
gets 376

DIBt:rlpllan Gets a line from the stdio stream.

#include <Stdio.h>

char *gets( char *buffer );

buffer Storage location for input string

The line consists of all characters up to and including the first newline character (\n). The
R1matkB The gets function reads a line from the standard input stream stdio and stores it in buffer.

gets function then replaces the newline character with a null character ('\0') before return­
ing the line. In contrast, the fgets function retains the newline character.

Relum Value If successful, the gets function returns its argument. A NULL pointer indicates an error or
end-of-file condition. Use ferror or feof to determine which one has occurred.

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

S11 AIBD fgets, fputs, puts

I * GETS . C *

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

v o i d ma i n ( )


(
c h a r l i n [ 81 ] ;

p r i n t f ( " I n put a s t r i n g : • ) ;
gets ( 1 i ne > ;
p r i n t f ( " T h e l i n e e n t e red w a s : % s \ n " , l i n e ) ;

�l
Output

I n put a s t i n g : T h i s i s a s t r i n g .
T h e l i o e e t e red wa s ' T h i s i s a s t r i og

I
377 _gettextcolor

D11Bt:r/pllan Gets the current text color.

#include <graph.h>

short _far _gettextcolor( void ) ;

R11matlcs The _gettextcolor function returns the color index o f the current text color. The text color
is set by the _settextcolor function and affects text output with the _outtext and _outmem
functions only. The _setcolor function sets the color for font text output using the
_outgtext function.
The default is 7 in test modes; it is the highest legal color index of the current palette in
graphics modes.

R11turn Valu11 The _gettextcolor function returns the color index of the current text color.

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

Se11 Alsa _getvideocontig, _remappalette, _selectpalette, _setcolor, _settextcolor

Examp/11 See the example for _gettextposition.


_gettextcu or 378

Dest:rlpllan Gets the current cursor attribute.

#include <graph.h>

short _far _gettextcursor( void );

Remarks The _gettextcursor function returns the current cursor attribute (i.e., the shape). This func­
tion works only in text video modes.

Rstum Value The function returns the current cursor attribute, or -1 if an error occurs (such as a call to
the function in a graphics mode).

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

See Also _displaycursor, _grstatus, _settextcursor

Example See the example for _settextcursor.


379 _gettextposition

Description Gets the current text position.

#include <graph.h>

struct rccoord _far _gettextposition( void );

Remarks The _gettextposition function returns the current text position as an rccoord structure,
defined in GRAPH.H.

The rc;coord structure contains the following elements:

Element Description
short row Row coordinate
short col Column coordinate

Remarks The text position given by the coordinates ( 1 , 1 ) is defined as the upper-left comer of the
text window.

Text output from the _outtext and _outmem functions begins at the current text position.
Font text is not affected by the current text position. Font text output begins at the current
graphics output position, which is a separate position.

Retum Value None.

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

See Also _getcurrentposition functions, _moveto functions, _outmem, _outtext,


_settextposition, _settextwindow, _wrapon

I * OUTTXT . C : T h i s exampl e i l l u s t r a t e s text output f u n c t i o n s :


* _g ettextc o l o r _g e t b k c o l o r _g ettextpos i t i o n _o uttext
* _s ettex t c o l o r _s e t b k c o l o r _s ettextpos i t i on
*I

#i n c l u d e < c o n i o . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < g ra p h . h >
_gettextp sition 380

c h a r b u f f e r [ 80 ] ;

v o i d ma i n ( ) j
,
I

I * Sa v e o i g i n a l f o r e g r o u n d , b a c k g round , a n d text po s i t i on . * /
s h o r t b l i k , fgd , o l d f g d ;
l ong bgd , o l dbgd ;

r
s t ruct re oord ol dpos :

I * S a v e o i g i n a l f o r e g round , b a c k g round , a n d text p o s i t i on . * /


ol dfgd = gettextcol o r < > :

I
o l dbgd = g e t b k c o l o r C > :
o l dpos = g e t t e x t p o s i t i o n C > :
_c l ea rs c r e e n ( _GC L EARSC R E E N > :

I * Fi r s t t i me n o bl i n k , s e c o n d t i me bl i n k i n g . * /
I
f o r ( bl i k = 0 : bl i n k <= 1 6 : b l i n k += 1 6 >
I
I * L o p t h ro u g h 8 ba c kg round c o l o r s . * /
fo r ( gd = 0 ; b g d < B : bgd++ >
{
_s t b k c o l o r ( bgd > :
_s t t extpos i t i on ( ( s h o r t ) bgd + ( ( bl i n k I 1 6 ) * 9 ) + 3 , 1 > :
_s t t ex t c o l o r C 7 > :
sp i n t f ( b u f fe r , " B a c k : %d F o r e : " , bgd > :
_o ttext ( buffer > :

ro l
I * Loop t h r o u g h 1 6 f o r e g r o u n d c o l o r s . * /
( f g d = 0 ; f g d < 1 6 ; fg d++ )

_s ettext c o l o r ( fgd + b l i n k > :


s p r i n t f ( b u f fe r , • %2d • , fgd + b l i n k > :
_ou t t ex t ( b u f f e r > :

[I
}


g} e t c h C > :

I* Rest �r e o r i g i n a l f o r e g r o u n d , b a c k g round , a n d t e x t pos i t i on . * /


_s e t t e x col o r ( ol dfgd ) ;
_s e t b k c l o r e o l dbgd > :
_c l ea r s reen ( _GC L EARSC R E E N ) ;
_s e t t e x pos i t i on ( o l dpos . row , o l dpos . c o l > :

I
I
381 _gettextwindow

Description Gets the boundaries of the current text window.

#include <graph.h>

void _far _gettextwindow( short _far *rl, short _far *cl , short _far *r2,
short _far *c2 );

rl Top row of current text window


cl Leftmost column of current text window
r2 Bottom row of current text window
c2 Rightmost column of current text window

Remarks The _gettextwindow function finds the boundaries of the current text window. The text
window is the region of the screen to which output from the _outtext and _outmem func­
tions is limited. By default, this is the entire screen, unless it has been redefined by the
_settextwindow function.
The window defined by _settextwindow has no effect on output from the _outgtext func­
tion. Text displayed with _outgtext is limited to the current viewport.

Return Value None.

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

See Also _gettextposition, _outmem, _outtext, _scrolltextwindow, _settextposition,


_settextwindow, _wrapon

Example See the example for _scrolltextwindow.


_getvide canfig 382

Dewipllan Gets graphics video configuration infonnation.

#include <graph.h>

struct videoconfig _far * _far __getvideoconfig( struct videoconfig _far *config );

config Configuration infonnation

Remarks The __getvideoconfig function returns the current graphics environment configuration in a
videoconfig structure, defined in GRAPH.H.
The values returned reflect the currently active video adapter and monitor, as well as the
current video mode.

The videoconfig structure contains the following members, each of which is of type short:

Member Contents
adapter Active display adapter
bitsperpixel Number of bits per pixel
memory Adapter video memory in kilobytes
mode Current video mode
monitor Active display monitor
numcolors Number of color indices
numtextcols Number of text columns available

numtextrows Number of text rows available


numvideopages Number of available video pages
numxpixels Number of pixels on the x axis

numypixels Number of pixels on the y axis


383 _getvideoconfig

The values for the adapter member of the videoconfig structure are given by the manifest
constants shown in the list below. For any applicable adapter ( _CGA, _EGA, or _VGA),
the corresponding Olivetti® adapter ( _OCGA, _OEGA, or _OVGA) represents a superset
of graphics capabilities.

Adapter Constant Meaning


_CGA Color Graphics Adapter
_EGA Enhanced Graphics Adapter
_HGC HerculeS® Graphics Card
_MCGA Multicolor Graphics Array
_M DPA Monochrome Display Printer Adapter
_OCGA Olivetti (AT&T®) Color Graphics Adapter
_OEGA Olivetti (AT&T) Enhanced Graphics Adapter
_OVGA Olivetti (AT&T) Video Graphics Array
_VGA Video Graphics Array

The values for the monitor member of the videoconfig structure are given by the manifest
constants listed below:

Monitor Constant Meaning


_ANALOG Analog monochrome and color
_ANALOGCOLOR Analog color only

_ANALOGMONO Analog monochrome only

_COLOR Color (or enhanced monitor emulating a color monitor)

_ENHCOLOR Enhanced color


_MONO Monochrome monitor

In every text mode, including monochrome, the _getvideoconfig function returns the value
32 for the number of available colors. The value 32 indicates the range of values (0-3 1)
accepted by the _settextcolor function. This includes 1 6 normal colors (0-15) and 1 6
blinking colors ( 16-3 1 ). Blinking is selected by adding 1 6 to the normal color index. Be­
cause monochrome text mode has fewer unique display attributes, some color indices are
redundant. However, because blinking is selected in the same manner, monochrome text
mode has the same range (0-3 1 ) as other text modes.
_getvideo nfig $ 384

Return Value The _getvideoconfig function returns the video configuration information in a structure, as
noted above. There is no error return.

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

See Also _setvideomode, _setvideomoderows

Example ��--���

j
I * GV I D C FG . C : T h i s p r o g r a m d i s p l a y s i n forma t i on a bout t h e c u r rent
* v i deo c o n f g u r a t i o n .
*/

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


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

�oi d ma i n ( ) I
s t ruct v i d � o c o n f i g v c ;
s h o rt c · •

char b [ 5�0 ] ; I * B u f f e r f o r s t r i ng * /

b
_get v i d e oc n f i g ( & v c ) ;


I * W r i t e a l i nf o rma t i o n to a s t r i ng , t h e n output s t r i n g . */
v c . numx p i x e l s l ;

l
c = s p r i nit f ( b , • X pi xe1 s : %d \ n " ,
c += s p r i � t f ( b + c , • y p i x e l s : %d\ n " , v c . n umy p i x e l s ) ;
c += s p r i ntf ( b + c , " Text c o l umn s : % d \ n " , v c . n umtext c o l s ) ;
c += s p r i t f ( b + c , " Text rows : %d\ n " , v c . n umt ex t r ow s ) ;
c += s p r i t f ( b + c , " Co l o r s : %d\ n " , v c . n umc o l o r s ) ;
c += s p r i t f ( b + c , " B i t s / p i x e l : %d\ n " , vc . bi tsperpi xel ) ;
c += s p r i t f ( b + c , " V i d e o p a g e s : %d \ n " , vc . numv i d e o p a g e s ) ;
c += s p r i ry t f ( b + c , " Mode : %d\n " , v c . mode ) ;

c += s p r i rl t f ( b + c , " Mon i t o r :
c += s p r i rt t f ( b + c , " Ad a pt e r : %d\ n " , vc . adapter ) ;

c += s p r i � t f ( b + c , " Memo ry :
%d\n " , vc . mon i t o r ) ;

_o utt ext ( b ) : l %d\ n " , vc . memo ry ) ;


385 _getvideoconfig

Output

X pi xel s : 0
Y pi xel s : 0
Text c o l umn s : 80
Text rows : 25
Col ors : 32
B i t s / p i xel : 0
V i deo pages : 1
M od e : 3
Ada p t e r : 8
M on i t o r : 24
Memo ry : 256
_getvieWi oord Functions 386

Descr/pllon Translate coordinates to view coordinates.

#include <graph.h>

struct xycoord .Jar _getviewcoord( short x, short y );


struct xycoord _far _getviewcoord_w( double wx, double wy );
struct xycoord _far _getviewcoord_wxy( struct _wxycoord _far *pwxyl );

x, y Physical point to translate


wx, wy Window point to translate
pwxyl Window point to translate

Remarks The _getviewcoord routines translate the specified coordinates (x, y) from one coordinate
system to view coordinates and then return them in an xycoord structure, defined in
GRAPH.ff. The xycoord structure contains the following elements:

Element Description
·
short xcoord x coordinate
short ycoord y coordinate

The various _getviewcoord routines translate in the following manner:

Routine Translation

_getviewcoord Physical coordinates (x, y) to view coordinates


_getviewcoord_w Window coordinates (wx, wy) to view coordinates

_getviewcoord_wxy Window coordinates structure (pwxyl ) to view coordinates

C 5. 1 Version Difference In Microsoft C version 5. 1, the function _gel'l/ewcoord was called


_gellogcoord.

Retum Value The _getviewcoord function returns the coordinates as noted above. There is no error
return.
387 _getviewcoord Functions

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

See Also _getphyscoord, _getwindowcoord, _grstatus

Example See the example for _setwindow.


f
I

_getvisu age 388

Description Gets the current visual page number.

#include <graph.h>

short _far _getvisualpage( void );

Remarks The _getvisualpage function returns the current visual page number.

Return Value The function returns the number of the current visual page. All hardware combinations sup­
port at least one page (page number 0). In OS/2, only page 0 is available.

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

See Also _getactivepage, _gettextcolor, _gettextposition, _outtext, _setactivepage,


_settextcolor, _settextposition, _settextwindow, _setvideomode,
_setvisualpage, _wrapon

Example See the example for _getactivepage.


389 getw

Description Gets an integer from a stream.

#include <Stdio.h>

int getw( FILE *stream );

stream Pointer to FILE structure

Remarks The getw function reads the next binary value of type int from the file associated with
stream and increments the associated file pointer (if there is one) to point to the next un­
read character. The getw function does not assume any special alignment of items in the
stream.

Return Value The getw function returns the integer value read. A return value of EOF may indicate an
error or end-of-file. However, since the EOF value is also a legitimate integer value, feof
or ferror should be used to verify an end-of-file or error condition.

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

The getw function is provided primarily for compatibility with previous libraries. Note
that portability problems may occur with getw, since the size of the int type and the order­
ing of bytes within the int type differ across systems.

See Also putw

/ * G ETW . C : T h i s p r o g r a m u s e s getw to r e a d a word f r om a s t r e a m ,


* t h en p e r f o rms a n e r r o r c h e c k .
*/

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

v o i d ma i n ( )
(

FI LE *stream ;
i nt i ;
getw 390

� l
( /*
i f ( C s t r e m = fopen ( " g etw . c • , " rb " > > == N U L L >

*/
r i n t f " C o u l d n ' t open f i l e \ n " > :
el s


f
. 1* */
Rea a word f rom t h e s t rea m :

l
i = ge w < s t r e a m ) ;

I f �here i s a n e r ro r . . •

i f ( f�r r o r ( s t r e a m ) )

1
(
p r ' n t f ( " g etw f a i l ed \ n " > :
c l a re r r ( s t r e a m ) ;

el se
p r ·· n t f { " Fi r s t d a t a w o r d i n f i l e : 0x% . 4x \ n " , );
f c l o s ( s t re a m > :

Output I
Fi rst data �ord i n fi l e : 0x2a 2f
391 _getwindowcoord

Description Translates view coordinates to window coordinates. .

#include <graph.h>

struct _wxycoord _far _getwindowcoord( short x, short y );

x, y Physical point to translate

Remal'ks The _getwindowcoord function translates the view coordinates (x, y) to window coordi­
nates and returns them in the _wxycoord structure, defined in GRAPH.ff.
The _wxycoord structure contains the following elements:

Element Description

double wx x coordinate
double wy y coordinate

Retum Value The function returns the coordinates in the _wxycoord structure. There is no error return.

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

See Also _getphyscoord, _getviewcoord functions, _moveto functions, _setwindow

Example See the example for _setwindow.


_getwrite ode 892

De1t:t/pllon Gets the current logical mode for line drawing.

#include <graph.h>

short _far _getwritemode( void );

Remarks The _getwritemode function returns the current logical write mode, which is used when
drawing lines with the _lineto, _polygon, and _rectangle functions.

The default value is _GPSET, which causes lines to be drawn in the current graphics color.
The other possible return values are _GXOR, _GAND, _GOR, and _GPRESET. See
_putimage for more details on these manifest constants.

Retum Value The _getwritemode function returns the current logical write mode, or -1 if not in
graphics mode.

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

S11 AIBD _grstatus, _lineto functions, _putimage functions, _rectangle functions,


_setcolor, _setlinestyle, _setwritemode

&ampm __ ______________________________________________________________ _

I * GW RMO D E . : T h i s p rog r�m i l l u s t r a t e s _g etw r i t emode a n d _s etw r i t emod e . * /

#i n c l u d e < �o n i o . h >
#i n c l ude < s t d l i b . h>
#i n c l ude < r a p h . h >

l:
( " P S ET •
_G P R ESET , _GX O R , _GO R , _GA N O
c h a r *wm s t [ S J = " P RE S ET " , " XO R •, "OR " " AN D " l:

v o i d box ( h o r t x , s ho rt y , s h o r t s i z e , s h o r t w r i t emod e , s h o rt f i l l mode > :

v o i d ma i n ( �
( i
s ho r t i x, y;
393 _getwritemode

I * F i nd a v a l i d g r a p h i c s mod e . * I
i f ( ! _s et v i d eomod e ( _MAX C O LO RM O D E ) )
exi t C 1 ) ;

x = y = 70 ;
box ( x , y , 50 , _G P S ET , _G F I L L I NT E R I O R ) ;
_s e t c o l o r C 2 ) ;
box ( x , y , 40 , _G P S ET , _G F I L L I NT E R I O R ) ;
fo r ( i = Iii ; i < 5 ; i ++ >
{
_s ettextpos i t i on ( l , 1 ) ;
_outtext ( wms t r [ i ] ) ;
box ( x += 1 2 , y += 1 2 , 50 , wmo d e s [ i ] , _GBO R D E R ) ;
getc h ( ) ;

_s e t v i d eomod e ( _D E FAU LTMO D E ) ;

v o i d box ( s h o r t x , s h o r t y , s h ort s i ze , s h o r t w r i t emod e , s h o r t f i l l mo d e )


{
s h o r t wm , s i d e ;

wm = _g etw r i t emode ( ) ; / * S a v e w r i t e mode a n d s e t new . * /


_s etw r i temod e C w r i t emode ) ;
_re c t a n g l e ( f i l l mo d e , x - s i z e , y - s i z e , x + s i ze , y + s i ze > ;
_s etw r i temod e ( wm ) ; / * Re s t o r e o r i g i n a l w r i t e mod e . * I
gmtime 394

DescripUon Converts a time v alue to a structure.

#include <time.h>

struct tm *gmtime( const time_t *timer );

timer Pointer to stored time

Rematks The gmtime function converts the timer value to a structure. The timer argument repre­
sents the seconds elapsed since 00:00:00, January l , 1 970, Greenwich mean time. This
value is usually obtained from a call to the timer function.
,
The gmtime function breaks down the timer value and stores it in a structure of type tm,
defined in TIME.H. (See asctime for a description of the structure members.) The struc­
ture result reflects Greenwich mean time, not local time.
The fields of the structure type tm store the following values, each of which is an int:
Field Value Stored

tm_sec Seconds
tm_min Minutes
tm_hour Hours (0-24)
tm_mday Day of month ( 1-3 1 )
tm_mon Month (0-1 1 ; January = 0)
tmJear Year (current year minus 1 900)

tm_wday Day of week (0- 6; Sunday = 0)


tmJday Day of year (0-365; January 1 = 0)

tm_isdst Always 0 for gmtime

The gmtime, mktime, and localtime functions use a single statically allocated structure to
hold the result. Each call to one of these routines destroys the result of any previous call.
DOS and OS/2 do not accommodate dates prior to 1 980. If timer represents a date prior to

-���
1 980, gmtime returns NULL.

The gmtime function returns a pointer to the structure result. There is no error return.

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


395 gmtime

See Also asctime, ctime, ftime, localtime, time

I * GMT I M E . C : T h i s p ro g r a m u s es gmt i me to c o n v e rt a l on g - i n t e g e r
* r e p r e s e n t a t i on of G reenwi c h mea n t i me to a s t r u c t u r e n a med n ewt i me ,
* t h e n u s e s a s c t i me to c o n v e r t t h i s s t r u c t u r e to a n o u t p u t s t r i n g .
*I

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


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

v o i d ma i n ( )
(
s t ruct tm * n ewt i me ;
l on g l t i me ;

t i me ( & l t i me ) ;

I * Obta i n G reenwi c h mea n t i me : * /


n ewt i me = gmt i me C & l t i me ) ;
p r i n t f ( " G reenw i c h mea n t i me i s % s \ n " , a s ct i me ( newt i me ) ) ;

Output

G r eenwi c h mea n t i me i s F r i J u n 1 6 1 6 : 3 7 : 53 1 989


_grstatus 396

Description Returns the status of the most recent graphics function call.

#include <graph.h>

short _far _grstatus( void );

Remarks The _grstatus function returns the status of the most recently used graphics function. The
_grstatus function can be used immediately following a call to a graphics routine to deter­
mine if errors or warnings were generated. Return values less than 0 are errors, and values
greater than 0 are warnings.
The following manifest constants are defined in the GRAPH.ff header file for use with the
_grstatus function:

Value Constant Meaning

0 _GROK Success
-1 _GRERROR Graphics error
-2 _GRMODENOTSUPPORTED Requested video mode not supported
-3 _GRNOTINPROPERMODE Requested routine only works in cer-
tain video modes
-4 _GRINVALIDPARAMETER One or more parameters invalid
-5 _GRFONTFILENOTFOUND No matching font file found
-6 _GRINVALIDFONTFILE One or more font files invalid
-7 _GRCORRUPTEDFONTFILE One or more font files inconsistent
-8 _GRINSUFFICIENTMEMORY Not enough memory to allocate buff-
er or to complete a _floodflll
operation
-9 _GRINVALIDIMAGEBUFFER Image buffer data inconsistent
1 _GRMOOUTPUT No action taken
2 _GRCLIPPED Output was clipped to viewport
3 _GRPARAMETERALTERED One or more input parameters was al-
tered to be within range, or pairs of
parameters were interchanged to be
in the proper order
397 _grstatus

After a graphics call, use an if statement to compare the return value of _grstatus to
_GROK. For example:
i f { _g r s t a t u s < _G RO K )
/ * h a n d l e g r a p h i c s e r ro r * /

The functions listed below cannot cause errors, and they all set _grstatus to GROK:

_displaycursor _gettextposition _outmem


_getactivepage _gettextwindow outtext
_getgtextvector _getvideoconfig _unregisterfonts
_gettextcolor _getvisualpage _wrapon

See the list below for the graphics functions that affect _grstatus. The list shows error or
warning messages that can be set by the graphics function. In addition to the error codes
listed, all of these functions can produce the _GRERROR error code.

Function Possible _grstatus Possible _grstatus


Error Codes Warning Codes

_arc functions GRNOTINPROPERMODE, GRNOOUTPUT,


:GRINVALIDPARAM:ETER :GRCLIPPED
_clearscreen GRNOTINPROPERMODE,
:GRINVALIDPARAM:ETER
..:.ellipse functions GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFICIENTMEMORY
_getarcinfo _GRNOTINPROPERMODE
_getcurrentposition _GRNOTINPROPERMODE
functions
_getfontinfo ( _GRERROR only)
_getgtextextent ( _GRERROR only)
_getgtextvector _GRPARAMETERALTERED
_getimage _GRNOTINPROPERMODE _GRPARAMETERALTERED
_getphyscoord _GRNOTINPROPERMODE
_getpixel _GRNOTINPROPERMODE
_gettextcursor _GRNOTINPROPERMODE
_getviewcoord functions _GRNOTINPROPERMODE

Continued on next page


_grstatus 398

Function Possible _grstatus Possible _grstatus


Error Codes Warning Codes

_getwindowc rd _GRNOTINPROPERMODE
_getwritemo _GRNOTINPROPERMODE
_imagesize fu ctions _GRNOTINPROPERMODE
_lineto functi ns _GRNOTINPROPERMODE GRNOOUTPUT,
:GRCLIPPED
_moveto func ons · _GRNOTINPROPERMODE
_outgtext _GRNOTINPROPERMODE GRCLIPPED,
:GRNOOUTPUT
_pie function GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFI CIENTMEMORY
_polygon fun 1 tions GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFICIENTMEMORY
_putimage GRERROR, GRPARAMETERALTERED,
-GRNOTINPROPERMODE, :GRNOOUTPUT
-GRINVALIDPARAMETER,
:GRINVALIDIMAGEBUFFER
_rectangle GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFICIENTMEMORY
_registerfon GRCORRUPI'EDFONTFILE,
-GRFONTFILENOTFOUND,
-GRINSUFFICIENTMEMORY,

_scrolltex
I ndow
:GRINVALIDFONTFILE
_GRNOOUTPUT
_selectpalet GRNOTINPROPERMODE,
:GRINVALIDPARAMETER
_GRINVALIDPARAMETER
_setbkcolor _GRINVALIDPARAMETER _GRPARAMETERALTERED
_setcliprgn _GRNOTINPROPERMODE _GRPARAMETERALTERED
_setcolor _GRNOTINPROPERMODE _GRPARAMETERALTERED
GRERROR,

I·r-
_setfont
-GRFONTFILENOTFOUND,
-GRINSUFFICIENTMEMORY,
:GRPARAMETERALTERED

Continued page
399 _grstatus

Function Possible _grstatus Possible _grstatus


Error Codes Warning Codes

_setgtextvector _GRPARAMETERALTERED
_settextcolor _GRPARAMETERALTERED
_settextcursor _GRNOTINPROPERMODE
_settextposition _GRPARAMETERALTERED
_settextrows _GRINVALIDPARAMETER _GRPARAMETERALTERED
_settextwindow _GRPARAMETERALTERED
_setvideomode _GRERROR,
_GRMODENOTSUPPORTED,
_GRINVALIDPARAMETER
_setvideomoderows _GRERROR,
_GRMODENOTSUPPORTED,
_GRINVALIDPARAMETER
_setvieworg _GRNOTINPROPERMODE
_setviewport _GRNOTINPROPERMODE _GRPARAMETERALTERED
_setvisualpage _GRINVALIDPARAMETER
_setwindow _GRNOTINPROPERMODE, _GRPARAMETERALTERED
_GRINVALIDPARAMETER
setwritemode _GRNOTINPROPERMODE,
_GRINVALIDPARAMETER

Return Value The _grstatus function returns the status of the most recently used graphics function.

See Also _arc functions, _ellipse functions, _tloodfill, _lineto functions, _pie functions,
_remapallpalette, _setactivepage, _setbkcolor, _setcolor, _setpixel functions,
_settextcolor, _settextcursor, _setvisualpage, _setwindow, _setwritemode

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


halloc 400

Description I Allocates a huge memory block.

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

void _huge *halloc( long num, size_t size );

num Number of elements


size Length in bytes of each element

Remarks The halloc function allocates a huge array from the operating system consisting of num ele­
ments, each of which is size bytes long. Each element is initialized to 0. If the size of the
array is greater than 1 28K ( 1 3 1 ,072 bytes), the size of an array element must then be a
power of 2.

Return Va/u i The halloc function returns a void huge 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
void huge, use a type cast on the return value. If the request cannot be satisfied, the return
I value is NULL.

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

See A/so I calloc functions, free functions, hfree, malloc functions


I


I * HALLOC!. C : T h i s p r o g r a m u s e s h a l l oc t o a l l o c a t e s p a c e f o r 30 , 000 l on g
* i n t e g e s , t h e n u s e s h f r e e t o d ea l l o c a t e t h e memo ry .
*I :
#i n c l u d e k s t d i o . h>
#i n c l u d e ( s t d l i b . h >
1/i n c l u d e r <ma l 1 o c . h >

rl
I
v o i d ma i < l
l
l on g l h u g e * h b u f ;
i

I
I
401 ha/lac

I * Al l o c a t e h u g e b u f f e r * /
h b u f = ( l on g _h uge * l h a l l oc ( 30000 L , s i zeof ( l ong l l ;
i f ( hbuf = NULL )
=

p r i n t f ( " I n s uffi c i ent memo ry a v a i l a b l e \ n " l ;


el se
p r i n t f ( " Memo ry s u c c e s s fu l l y a l l o c a t ed \ n " l ;

I * Free h u g e b u ffe r * /
hfree ( hbuf ) ;

Output

Memo ry s u c c e s s fu l l y a l l o c a t ed
402

I
Description Handle critical error conditions.

#include <dos.h>

void _harderr( void( _far *handler )( ));


void _hardresume( int result );

void _hardretn( int error );

handler ( ) New INT Ox24 handler


result Handler return parameter
error Error to return from

Remarks These three functions are used to handle critical error conditions that use DOS interrupt
Ox24. The _harderr function installs a new critical-error handler for interrupt Ox24.

the new critical-error handler installed by _harderr. The _hardresume function returns to
The hardresume and hardreturn functions control how the program will return from

directly to the application program from a user-installed critical-error handler.


DOS from a user-installed critical-error handler, and the hardreturn function returns

The _harderr function does not directly install the handler pointed to by handler; instead,

the function with the following parameters:


harderr installs a handler that calls the function referenced by handler. The handler calls

handler(unsigned deverror, unsigned errcode, unsigned far *devhdr);

The deverror argument is the device error code. It contains the AX register value passed
by DOS to the INT Ox24 handler. The errcode argument is the DI register value that DOS
passes to the handler. The low-order byte of errcode can be one of the following values:

Code Meaning

0 Attempt to write to a write-protected disk


1 Unknown unit
2 Drive not ready
3 Unknown command
4 Cyclic-redundancy-check error in data
5 Bad drive-request structure length
403 _hard Functions

6 Seek error
7 Unknown media type
8 Sector not found
9 Printer out of paper
10 Write fault
11 Read fault

12 General failure

The devhdr argument is a far pointer to a device header that contains descriptive informa­
tion about the device on which the error occurred. The user-defined handler must not
change the information in the device-header control block.

Errors on Disk Devices

If the error occurred on a disk device, the high-order bit (bit 15) of the deverror argument
will be set to 0, and the deverror argument will indicate the following:

Bit Meaning

15 Disk error if false (0).

14 Not used.

13 "Ignore" response not allowed if false (0).

12 "Retry" response not allowed if false (0).

11 "Fail" response not allowed if false (0). Note that DOS


changes "fail" to "abort".

10, 9 Code Location

00 DOS
01 File allocation table

10 Directory

11 Data area

8 Read error if false; write error if true.


_hard Futctions
I
404

The low-order byte of deverror indicates the drive in which the error occurred (0 = drive
A, 1 = drive B, etc.).

Errors on Other Devices

ff the error occurs on a device other than a disk drive, the high-order bit (bit 1 5) of the
deverror argument is 1 . The attribute word located at offset 4 in the device-header block in­
dicates the type of device that had the error. If bit 1 5 of the attribute word is 0, the error is
a bad memory image of the file allocation table. If the bit is l, the error occurred on a char­
acter device and bits 0-3 of the attribute word indicate the type of device, as shown in the
following list:

Bit Meaning

0 Current standard input


1 Current standard output
2 Current null device
3 Current clock device

Restrictions on Handler Functions

The user-defined handler function can issue only system calls OxOl through OxOC, or
Ox59. Thus, many of the standard C run-time functions (such as stream 1/0 and low-level
1/0) cannot be used in a hardware error handler. Function Ox59 can be used to obtain
further information about the error that occurred.

Using _hart/resume and _harde"

If the handler returns, it can do so

1. From the return statement


2. From the _hardresume function
3. From the _hardretn function

If the handler returns from -hardresume or from a return statement, the handler returns
to DOS.
405 _hard Functions

The _hardresume function should be called only from within the user-defined hardware
error-handler function. The result supplied to _hardresume must be one of the following
constants:

Constant Action

_HARDERR_ABORT Abort the program by issuing INT Ox23


_HARDERR_FAIL Fail the system call that is in progress (this is not supported on
DOS 2. x)

_HARDERR_IGNORE Ignore the error

_HARDERR_RETRY Retry the operation

The _hardretn function allows the user-defined hardware error handler to return directly
to the application program rather than returning to DOS. The application resumes at the
point just after the failing 1/0 function request. The _hardretn function should be called
only from within a user-defined hardware error-handler function.

The error parameter of _hardretn should be a DOS error code, as opposed to the XENIX­
style error code that is available in errno. Refer to MS-DOS Encyclopedia (Duncan, ed.;
Redmond, Wa.: Microsoft Press, 1 988) or Programmer's PC Sourcebook (Hogan; Red­
mond, Wa. : Microsoft Press, 1988) for infonnation about the DOS error codes that may be
returned by a given DOS function call.

If the failing 1/0 function request is an INT Ox2 l function greater than or equal to function
Ox38, _hardretn will then return to the application with the carry flag set and the AX reg­
ister set to the _hardretn error parameter. If the failing INT Ox2 l function request is less
than function Ox38 and the function can return an error, the AL register will be set to OxFF
on return to the application. If the failing INT Ox2 l does not have a way of returning an
error condition (which is true of certain INT Ox2 1 functions below Ox38), the error param­
eter of _hardretn is not used, and no error code is returned to the application.

Return Value None.

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

SBB A/sa _chain_intr, _dos_getvect, _dos_setvect


_heapad Functions 406

Oesarlpllan Add memory to the heap lheapadd) or to the based heap lbheapadd).

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

int _heapadd( void _far *memblock, size_t size );


int _bheapadd( _segment seg, void _based (void) *memblock, size_t size );

seg Based-heap segment selector

buffer Pointer to heap memory

size Size in bytes of memory to add

Rematits The _heapadd and _bheapadd functions add an unused piece of memory to the heap. The
_bheapadd function adds the memory to the based heap specified by seg. The _heapadd
function looks at the segment value and, if it is DGROUP, adds the memory to the near
heap. Otherwise, _heapadd adds the memory to the far heap.

Retum Value These functions return 0 if successful, or -1 if an error occurred.

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

See Also free functions, halloc, hfree, malloc functions, realloc functions

Exampm __ -1--------------------------------------------------------------

I * H EA PM I N . C : T h i s p ro g r a m i l l u s t r a t e s h e a p m a n a gement u s i ng
* _h e a p a d a nd _h e a pmi n .


*/

#i n c l u d e < t d i o . h>
#i n c l u d e < oni o . h>
#i n c l u d e < rocess . h>
#i n c l u d e < a l l oc . h >

I
407 _heapadd Functions

v o i d h e a p d ump C c h a r *ms g > : I * P rot otype * /

c h a r s l [ ] = I " He re a re s ome s t r i n g s t h a t w e u s e a t f i r s t , t h e n d o n ' t \ n " I :


cha r s2[] I " n eed a ny more . We ' l l g i v e t h e i r s p a c e t o t h e hea p . \ n " ) ; ,
=

v o i d ma i n ( )
(
i nt * p [ 3 ] , i :

p r i ntf C " % s %s " , s l , s 2 > :


h e a pd ump C " I n i t i a l h ea p • ) ;

I * Gi v e s p a c e of u s ed s t r i n g s t o h ea p . * /
_hea p a d d ( s l , s i z e o f ( s l ) > :
_h e a p a d d ( s 2 , s i z e o f ( s 2 ) > :
h e a pd ump C " After a dd i n g u s ed s t r i n g s • > :

I * Al l o c a t e s ome b l o c k s . Some may u s e s t r i n g b l o c k s f rom _he a p a d d . * /


for ( i =0 ; i < 2 ; i ++ )
i f( Cp[i ] = ( i nt * > ca l l oc C 1 0 * C i + 1 ) , s i zeof C i n t > > > == NU L L >
(
--i :
b r ea k ;
}
h e a pdump C " After a l l o c a t i ng memo ry • l;

/ * Free s ome of t h e b l o c k s . * /
f ree < p [ l ] > :
f ree ( p [ 2 ] ) ;
h e a pd ump C " After f r e e i n g memo ry • ) ;

I * M i n i mi z e h ea p . * /
_h e a pmi n C > ;
h e a pdump C " After c ompa c t i ng h ea p • > :

I * Wa l k t h ro u g h h e a p e n t r i e s , d i s p l a y i n g i n f o rma t i on a bo u t e a c h b l oc k . * /
v o i d h e a pd ump C c h a r *ms g )
( .
s t ruct _hea p i n fo h i ;

pri ntf( "%s\ n " , msg > :


h i . _pen t ry = N U L L ;
w h i l e ( _h e a pwa l k C & h i ) =-- _H EA P O K )
p r i n t f ( " \ t%s b l o c k a t % Fp of s i ze % u \ t \ n " ,
h i ._u s efl a g
== _U S E D ENTRY ? " U S E D " : " FR E E " ,
h i . _p e n t ry ,
h i . _s i z e ) ;
g et c h ( ) ;
1
_heapad Functions 408


Output

H e r e a re s o ' e s t r i n g s t h a t we u s e a t f i r s t , t h e n don ' t


n e ed a ny mo e . We ' l l g i v e t h e i r s p a c e to t h e h ea p .
I n i t i a l hea
U S ED b l o k a t 2 D 3 9 : 0 E 9 C of s i z e 3 6 4
U S E D b l o q k a t 2 D 3 9 : 100A of s i z e 3 6

l
U S E D b l o c k a t 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o k a t 2 D 3 9 : 1 232 of s i z e 460
After a d d i n u s ed s t r i n g s
F R E E b l o k a t 2 D 3 9 : 0044 of s i z e 5 2
F R E E b l o ¢ k a t 2D39 : 007A of s i z e 50
U S E D b l o ¢ k a t 2 D 3 9 : 00A E of s i ze 3 5 64
U S E D b l o � k a t 2 D 3 9 : 0 E9C of s i ze 364

l
U S E D b l o ¢ k at 2 D3 9 : 1 00A of s i z e 36
USED b l o f k at 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o k a t 2D39 : 1 2 3 2 of s i z e 460
Afte r a l l oc t i n g memo ry
U S E D b l o k a t 2 D 3 9 : 0044 of s i z e 20

i
U S E D b l o � k a t 2 D 3 9 : 005A