You are on page 1of 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 of s i z e 4 0
F R E E b l o f k a t 2 D 3 9 : 0084 of s i ze 40
U S E D bl o p k a t 2 D 3 9 : 00AE of s i z e 3 5 64
U S E D b l o k a t 2 D 3 9 : 0 E 9 C of s i z e 364
USED b l o k a t 2 D 3 9 : 100A of s i z e 3 6


U S E D b l o k a t 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o F k a t 2 D 3 9 : 1 2 3 2 of s i z e 460
Aft e r f r e e i r g memo ry
U S E D b l o k a t 2 D 3 9 : 0044 of s i z e 20
F R E E b l o k a t 2 D 3 9 : 005A of s i z e 40
FREE b l o k at 2 D 3 9 : 0084 of s i z e 40

USED bl ofc k a t 2 D 3 9 : 0 E 9 C o f s i z e 364


U S E D b l o,c k a t 2 D 3 9 : 00AE o f s i z e 3564

U S E D b l Qc k a t 2 D 3 9 : 100A o f s i z e 3 6
U S E D b l � c k a t 2 D 3 9 : 1030 o f s i ze 5 1 2
F R E E b l 9 c k a t 2 D 3 9 : 1 232 o f s i z e 460

After c omp c t i n g h e a p
U S E D b l c k a t 2D39 : 0044 of s i z e 2 0
F R E E b l c k a t 2 D 3 9 : 005A of s i z e 8 2

�q
U S E D b l oc k a t 2 D 3 9 : 00AE o f s i z e 3564
USED b l c k a t 2 D 3 9 : 0 E 9 C o f s i z e 364
U S E D b l c k a t 2 D 3 9 : 1 00A o f s i z e 3 6
U S E D b l c k a t 2D39 : 1030 of s i ze 5 1 2
F R E E b l c k a t 2 D 3 9 : 1 232 o f s i z e 1 2
409 _heapchk Functions

Description Run consistency checks on the heap.

#include <malloc.h>

int _heapchk( void );

int _bheapchk( _segment seg );


int _tbeapchk( void );
, int _nheapchk( void );

seg Specified base heap

R1mam The _heapchk routines help to debug heap-related problems by checking for minimal con­
sistency of the heap.

Each function checks a particular heap, as listed below:

Function Heap Checked

_heapchk Depends on data model of program

_bheapchk Based heap specified by seg value

_tbeapchk Far heap (outside the default data segment)


_nheapchk Near heap (inside the default data segment)

In large data models (that is, compact-, large-, and huge-model programs), _heapchk maps
to _tbeapchk. In small data models (tiny-, small-, arid medium-model programs),
_heapchk maps to _nheapchk.

Return Value All four routines return an integer value that is one of the following manifest constants (de­
fined in MALLO C.H):

Constant Meaning

_HEAPBADBEGIN Initial header infonnation cannot be found, or it is bad


_HEAPBADNODE Bad node has been found, or the heap is damaged
_HEAPEMPTY Heap has not been initialized
_HEAPOK Heap appears to be consistent

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


_heapchk unctions 410

SBB AIBa _heapset functions. _heapwalk functions

r
=r
Examp• �� �����������������������---���­
' * H EA P CH K . C T h i s p r � g r a m c he c k s t h e h e a p for c o n s i s t ency
* a nd p r i n t s an a p p r op r i a t e mes s a ge .
*I
I
�l
1
#i n c l u d e <ma l oc . h>
#i n c l ude < s t i o . h >

v o i d ma i n < >
(
i nt h e a p t a t u s :
c h a r *buf er :

I * Al l o c a e a nd d ea l l o c a t e s ome memory * /
i f { C b uff r - ( c h a r * ) ma l l oc C 100 ) ) ! = N U L L
free ( u f f e r > :

I* Check eap status */


heapstatu = _h e a p c h k C ) ;
s w i tc h ( h a ps t a t u s )
.

(
case _ EAPOK :
pri tfC " OK - heap i s fi ne\n " ) ;
bre k:
case - EAP EMPTY :
pri tfC " OK - h e a p i s empty \ n " > :
bre k:
case - E A P BADB E G I N :
pri t f C " E RROR - b a d s t a rt of h e a p \ n " > :

'T '
bre k:
case - EAPBADNO D E :
i
pri t f C " E R RO R - b a d n o d e i n hea p \ r " > :

Output I
OK - heap i � f i ne
411 _heapmin Functions

Description Release unused heap memory to the operating system.

#include <malloc. h>

int _heapmin( void ) ;


int _bheapmin( _segment seg )

int _theapmin( void );


int _nheapmin( void ) ;

seg Specified based-heap selector

Rematlrs The _heapmin functions minimize the heap by releasing unused heap memory to the oper­
ating system.

The various _heapmin functions release unused memory in these heaps:

Function Heap Minimized

_heapmin Depends on data model of program

_bheapmin Based heap specified by seg value; _NULLSEG specifies all


based heaps

_theapmin Far heap (outside default data segment)


_nheapmin Near heap (inside default data segment)

In large data models (that is, compact-, large-, and huge-model programs), _heapmin
maps to _theapmin. In small data models (tiny-, small-, and medium-model programs),
_heapmin maps to _nheapmin.

Based-heap segments are never freed (i.e., unlinked from the based heap list and released
back to the operating system) by the _bheapmin function. The _bfreeseg function is used
for that purpose.

Return Value The _heapmin functions return 0 if the function completed successfully, or -1 in the case
of an error.

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

See A/sa _bfreeseg, free functions, malloc functions


_heapse Funcllons 412

DBScrlptlon Check heaps for minimal consistency and set the free entries to a specified value.

#include <malloc.h>

int _heapset( unsigned int.fill ) ;


int _bheapset( _segment seg, unsigned int.fill );
int _fheapset( unsigned int.fill );
int _nheapset( unsigned int.fill ) ;

fill Fill character

seg Specified based-heap segment selector

Remarks The _heapset family of routines helps debug heap-related problems in programs by show­
ing free memory locations or nodes unintentionally overwritten.

The _heapset routines first check for minimal consistency on the heap in a manner identi­
cal to that of the _heapchk functions. After the consistency check, the _heapset functions
set each byte of the heap's free entries to the fill value. This known value shows which
memory locations of the heap contain free nodes and which locations contain data that
were unintentionally written to freed memory.

The various _heapset functions check and fill these heaps:

Function Heap Filled

_heapset Depends on data model of program

_bheapset Based heap specified by seg value; _NULLSEG specifies all


based heaps

_fheapset Far heap (outside default data segment)

_nheapset Near heap (inside default data segment)

In large data models (that is, compact-, large-, and huge-model programs), _heapset maps
to _fheapset In small data models (tiny-, small-, and medium-model programs), _heapset
maps to _nheapset
413 _heapset Functions

Return Value All four routines return an int whose value is one of the following manifest constants
(defined in MALLOC.H):

Constant Meaning

_HEAPBADBEGIN Initi al header information cannot be found, or it is invalid


_HEAPBADNODE Bad node has been found, or the heap is damaged

_HEAPEMPTY Heap has not been initialized

_HEAPOK Heap appears to be consistent

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

See Also _heapchk functions, _heapwalk functions

/ * H EA P S ET . C : T h i s p r o g r a m c h e c k s t h e h e a p a n d f i l l s i n f r e e en t r i e s
* wi th the cha racter Z ' ' .

*/

#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 >
#i n c l u d e < s td l i b . h >

v o i d ma i n ( )
(
i nt heapstatus :
c h a r *buffe r :

I
_heapse FuncUons 414

I
i f ( C b u f �e r ma l l oc C 1 ) )
= == NULL I * M a k e s u re h e a p i s i n i t i a l i z ed * /

h e a p s t a tJs
exi t ( 1 0 ) ;
= _h e a p s et C ' Z ' l : I * F i l l i n f re e e nt r i es * /
swi t c h ( � e a p s t a t u s )
(


c a s e i H EAPOK :

br�a k ;
p r n t f ( " O K - h e a p i s fi n e \ n " ) :

c a s e JH EAP EM PTY :
p r � n t f ( " O K - h e a p i s empty \ n " ) ;
b r�a k ;
c a s e JH E A P BADB E G I N :
p r � n t f ( " E RROR - b a d s t a rt o f h e a p \ n " ) ;
b r ea k ;
c a s e JH EA P BADNOD E :
p r � n t f ( " E RROR - b a d n o d e i n h e a p \ n " l ;
b r ea k ;


f ree ( bu f e r ) ;
I

Output

OK - hea p fi ne
415 _heapwalk Functions

Descrlpl/on Traverse the heap and return information about the next entry.

include <malloc.h>

int _heapwalk( _HEAPINFO *entryirrfo );


int _bheapwalk( _segment seg, _HEAPINFO *entryinfo );
int _tbeapwalk( _HEAPINFO *entryinfo );
int _nheapwalk( _HEAPINFO *entryirrfo);

entryinfo Buffer to contain heap information


seg Based-heap segment selector

Remarks The _heapwalk family of routines helps debug heap-related problems in programs.

The _heapwalk routines walk through the heap, traversing one entry per call, and return a
pointer to a _heapinfo structure that contains information about the next heap entry. The
_heapinfo structure, defined in MALLOC.H, contains the following elements:

Element Description

int far *_pentry Heap entry pointer

size_t _size Size of heap entry

int _useflag Entry "in use" flag

A call to _heapwalk that returns _HEAPOK stores the size of the entry in the _size field
and sets the _useflag field to either _FREEENTRY or _USEDENTRY (both are constants
defined in MALLOC.H). To obtain this information about the first entry in the heap, pass
the _heapwalk routine a pointer to a _heapinfo structure whose _pentry field is NULL.
The various _heapwalk functions walk through and gather information on these heaps:

Function Heap Walked


_heapwalk Depends on data model of program
_bheapwalk Based heap specified by seg value; _NULLSEG specifies all
based heaps

_tbeapwalk Far heap (outside default data segment)


_nheapwalk Near heap (inside default data segment)
.....heapwal Functions 416

In large data models (that is, compact-, large-, and huge-model programs), _heapwalk
maps to _theapwalk. In small data models (tiny-, small-, and medium-model programs),
_heapwalk maps to _nheapwalk.

Return Value All three routines return one of the following manifest constants (defined in MALLO C.H):

Constant Meaning

_HEAPBADBEGIN The initial header information cannot be found, or it is invalid.

_HEAPBADNODE A bad node has been found, or the heap "is damaged.

_HEAPBADPTR The _pentry field of the _heapinfo structure does not contain
a valid pointer into the heap. ·

_HEAPEND The end of the heap has been reached successfully.

_HEAPEMPTY The heap has not been initialized.

_HEAPOK No errors so far; the _heapinfo structure contains information


about the next entry.

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

See Also _heapchk functions, _heapset functions

I * H EAPWA L K . C T h i s p r o g r a m " wa l k s " t h e h ea p , s t a r t i n g a t t h e beg i n n i n g


* C _pent ry = N U L L ) . I t p r i nts out e a c h h e a p ent ry ' s u s e , l oc a t i on ,
* a nd s i z e . t a l s o p r i n t s out i n f o rma t i on a bout t h e o v e ra l l s t a t e
* o f t h e h e a a s s o o n a s _hea pwa l k r e t u r n s a v a l ue o t h e r t h a n _H EAPO K .
*I

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


#i n t l ude <ma l o c . h >
417 _heapwalk Functions

v o i d h e a pd ump ( v o i d ) ;

v o i d ma i n ( )
{
c h a r *buffe r ;

h e a pdump ( ) ;
i f ( ( bu f f e r = ma l l oc ( 5 9 > > ! = N U L L >
{
h e a pdump ( ) ;
free ( buffer ) ;
J
h e a pdump ( ) ;

v o i d h e a p d ump ( v o i d
{
s t r u c t _hea p i n fo h i n fo ;
i nt hea p s t a t u s ;

h i n fo . _p e n t ry = N U L L ;
w h i l e < < h e a p s t a t u s = _h e a pwa l k ( & h i nfo > > == _H EAPOK
{
p r i n t f ( " %6 s b l o c k a t % Fp of s i ze %4 . 4 X \ n " ,
( h i n f o . _u s e f l a g == _U S E D E NT RY ? " U S E D " : " F R E E " ) ,
h i n f o . _pent ry , h i n f o . _s i z e ) ;

s w i tc h ( h e a p s t a t u s )
{
c a s e _H E A P E M PTY :
p r i n t f ( " O K - empty h ea p \ n " > :
b r ea k ;
c a s e _H EAP E N D :
p r i n t f ( " O K - end o f h ea p \ n " ) ;
b r ea k ;
c a s e _H EAPBAD PT R :
p r i n t f ( " E RRO R - b a d p o i n t e r to h ea p \ n " > :
b r ea k ;
c a s e _H EAPBADB E G I N :
p r i n t f ( " E RRO R - b a d s t a rt of h ea p \ n " ) ;
brea k ;
c a s e _H EAPBADN OD E :
p r i n t f ( " E RROR - b a d node i n h ea p \ n " ) ;
brea k ;
_heapwalk Functions 418

l
Output

U S E D b l o c k a t 0067 : 10 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 104E of s i ze 0 1 F4

l
U S E D b l o c k ! a t 0067 : 1 244 of s i ze 0026
USED b l o c k a t 0067 : 1 2 6 C of s i ze 0200
FREE b l o c k at 006 7 : 1 4 6 E of s i ze 0890
OK - end o f h e a p
U S E D b l o c k a t 0067 : 1 0 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 10 4 E of s i ze 0 1 F4

l
U S E D b l o c k a t 0067 : 1 244
USED b l o c k a t 0067 : 1 2 6 C
USED b l o c k at 0067 : 14 6 E
of
of
of
s i ze
s i ze
s i ze
0026
0200
003C
FREE b l o c k , a t 006 7 : 14AC of s i ze 0852
OK - end of h e a p
U S E D b l o c k a t 006 7 : 1 0 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 1 04E of s i ze 0 1 F4
U S E D b l o c k a t 0067 : 1 244 of s i ze 0026
USED b l o c k at 0067 : 1 2 6 C of s i ze 0200

FREE b l o c k l a t 0067 : 14AC


FREE b l o c k ! a t 0067 : 14 6 E of s i ze 003C

end o f � e a p
of s i ze 0852
OK -
419 hfree

Dncrlptlon Frees a huge memory block.

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

void hfree( void _huge *memblock );

memblock Pointer to allocated memory block

Rematits The hfree function deallocates a memory block; the freed memory is returned to the oper­
ating system. The memblock argument points to a memory block previously allocated
through a call to halloc. The number of bytes freed is the number of bytes specified when
the block was allocated.

Note that attempting to free an invalid memblock argument (one not allocated with halloc)
may affect subsequent allocation and cause errors.

Retum Va/us None.

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

See Also halloc

I * H A L LOC . C : T h i s p ro g r a m u s e s h a l l oc to 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 r 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 memory .
*I

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


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

v o i d ma i n ( )
(
l ong _h u g e * h buf :

/ * Al l o c a t e h u g e buffer * /
h b u f - < l on g _h u g e * ) h a l l oc < 30000 L , s i zeof C l on g > > :
i f ( hbuf � NULL )
p r i n t f ( " I n s u f f i c i ent memo ry a v a i l a b l e \ n " > :
el se
p r i n t f ( " Memory s u c c e s s fu l l y a l l o c a t ed \ n " > :
hfree 420

/ * Free h ge buffer * /
h f ree < h b f ) ;

Output

Memo ry s u c c e s f u l l y a l l oca t ed
421 hypot, hypotl

DBScrlpllon Calculate the hypotenuse.

#include <math.h>

double hypot( double x, double y );


long double hypotl( long double x, long double y );

x, y Floating-point values

Remarks The hypot and hypotl functions calculate the length of the hypotenuse of a right triangle,
given the length of the two sides x and y (or xi and yl). A call to hypot is equivalent to the
following:

The hypotl function 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.

Return Value The functions return the length of the hypotenuse. If an overflow results, the functions re­
turn HUGE_VAL and set errno to ERANGE.

Compatlblllty hypot

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

hypotl

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

See Also cabs

I * H Y P OT . C : T h i s p r o g r a m p r i n t s t h e hypot e n u s e of a r i g h t t r i a n g l e . * /

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


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

v o i d ma i n ( )
(

l
doubl e x 3.0, y = 4.0;

p r i n t f ( " l f a r i g h t t r i a ng l e h a s s i des %2 . l f a n d %2 . l f , •
" i t s hypot e n u s e i s % 2 . l f \ n " , x , y , hypot ( x , y > > ;

Output
II
I f a r i g h t t r i a n gl e h a s s i des 3 . 0 a n d 4 . 0 , i t s hypot e n u s e i s 5 . 0
423 _imagesize Functions

Description Get amount of memory required to store graphics images.

#include <graph.h>

long _far _imagesize( short xl , short yl , short x2, short y2 );


long _far _imagesize_w( double wxl , double wyl, double wx2, double wy2 );
long _far _imagesize_wxy( struct _wxycoord _far *pwxyl ,
struct _wxycoord _far *pwxy2 );

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

Remarks The functions in the _imagesize family return the number of bytes needed to store the
image defined by the bounding rectangle and specified by the coordinates given in the
·

function call.
The _imagesize function defines the bounding rectangle in terms of view-coordinate
points (xl , yl ) and (x2, y2).
The _imagesize_w function defines the bounding rectangle in terms of window-coordinate
points (xl , yl ) and (x2, y2).
The _imagesize_wxy function defines the bounding rectangle in terms of the window­
coordinate pairs pwxyl and pwxy2.
The number of bytes needed to store the image is determined by the following formula:
xwi d = a b s ( x l - x 2 ) + 1 ;
ywi d = a b s C y l - y 2 ) + 1 ;
s i z e = 4+ C C l on g ) C C xw i d * b i t s_p e r_p i x e l +7 ) / 8 ) * ( 1 o n g ) yw i d ) ;

A call to _getvideocontig stores the b i t s_p e r _p i x e l information in the bitsperpixel


field of a videocontig structure.

Return Value The function returns the storage size of the image in bytes. There is no error return.

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


I
t
_lmages e Functions 424

I
I
See Also _getimage functions, _getvideocontig, _putimage functions

Example See the example for _getimage.


425 inp, inpw

Dacr/pllan Input a byte (inp) or a word (inpw) from a port.

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

int inp( unsigned port );


unsigned inpw( unsigned port );

port Port number

Remarks The inp and inpw functions read a byte and a word, respectively, from the specified input
port. The input value can be any unsigned integer in the range 0 65,535 .
-

To use inp and inpw in OS/2 protected mode, you must use a .DEF file to declare the
IOSEG segment that the run-time library uses to perform input/output on the port. In addi­
tion, the intrinsic (/Oi) versions of these functions do not work unless you put the code in a
. segment that is marked with the IOPL keyword in the .DEF file.
Because you cannot do IOPL from a regular code segment, the run-time library
declares a separate code segment called _IOSEG. In order to use inp, inpw, outp,
or outpw in any of the protected-mode run-time libraries (?LIBCP, LLIBCDLL,
LLIBCMT, or CDLLOBJS-based DLL), you must have a .DEF file containing this line:
S E GMENTS _ I O S E G C LASS ' I OS E G_COD E ' I O P L

Return Value The functions return the byte or word read from port. There is no error return.

Campallblllty 0 ANSI • DOS • OS2 0 UNIX 0 XENIX

See Also outp, outpw

Example See the example for outp.


int86 426

Description Executes the 8086 interrupt.

#include <dos.h>

int int86( int intnum, union REGS *inregs, union REGS *outregs );

intnum Interrupt number

inregs Register values on call

outregs Register values on return

Rematts The int86 function executes the 8086-processor-family interrupt specified by the interrupt
number intnum. Before executing the interrupt, int86 copies the contents of inregs to the
corresponding registers. After the interrupt returns, the function copies the current register
values to outregs. It also copies the status of the system carry flag to the cflag field in the
outregs argument. The inregs and outregs arguments are unions of type REGS. The union
type is defined in the include file DOS.H.

Do not use the int86 function to call interrupts that modify the DS register. Instead, use the
int86x function. The int86x function loads the DS and ES registers from the segregs para­
meter and also stores the DS and ES registers into segregs after the function call.

The REGS type is defined in the include filt1 DOS.H.

Return Value The return value is the value in the AX register after the interrupt returns. If the cftag field
in outregs is nonzero, an error has occurred; in such cases, the -dosermo variable is also
set to the corresponding error code.

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

See Also bdos, int86:x, intdos, intdosx

I * I NT86 . C T h i s p r o g ram u s e s i n t86 to c a l l t h e B I OS v i deo s e rv i c e


* ( I NT 1 0 ) t o g e t i n f o rma t i on a bo u t t h e c u r s o r .
*I

Iii n c l u d e < o s . h >


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

v o i d ma i n { )
(
u n i on REGS i n regs , o u t r e g s ;

I * Set up t o get c u r s o r i n forma t i on . * /


i n regs . h . a h = 3 ; / * Get C u r s o r Po s i t i on f u n c t i on * /
i n r egs . h . b h =0; / * Page 0 */

I * Exec u t e v i deo i n t e r rupt : * /


i n t86 { 0 x l 0 , & i n r e g s , & o u t r e g s ) ;

/ * Di s p l a y r e s u l t s . * /
p r i n t f { " C u r s o r po s i t i on \ n \ t Row : % d \ n \ t C o l umn : %d \ n " ,
o u t r e g s . h . d h , o u t regs . h . d l l ;

p r i n t f { " C u r s o r s h a pe \ n \ t St a r t : %d \ n \ t End : % d \ n " ,


outregs . h . c h , outregs . h . cl l ;

Output

C u r s o r po s i t i on
Row : 2
C o l umn : 0
Cursor shape
Sta rt : 6
End : 7
int86x

Description
I Executes the 8086 interrupt; accepts segment-register values.
428

#include <dos.h>

int int86x( int intnum, union REGS *inregs, union REGS *outregs,
struct SREGS *segregs );

intnum Interrupt number


inregs Register values on c all
outregs Register values on return
segregs Segment-register values on call

Remarks The int86x function executes the 8086-processor-family interrupt specified by the inter­
rupt number intnum. Unlike the int86 function, int86x accepts segment-register values in
segregs, enabling programs that use large-model data segments or far pointers to specify
which segment or pointer should be used during the system call.
Before executing the specified interrupt, int86x copies the contents of inregs and segregs

After the interrupt returns, the function copies the current register values to outregs, cop­
· to the corresponding registers. Only the DS and ES register values in segregs are used.

ies the current ES and OS values to segregs, and restores DS. It also copies the status of
the system carry flag to the ctlag field in outregs.
The REGS and SREGS types are defined i n the include file DOS.ff.
.
Segment values for the segregs argument can be obtained by using either the segread func­
tion or the FP_SEG macro.

Return Value The return value is the value in the AX register after the interrupt returns. If the cflag field
in outregs is nonzero, an error has occurred; in sucli cases, the _dosermo variable is also
set to the corresponding error code.

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

See Also bdos, FP_SEG, int86, intdos, intdosx, segread


429 int86x

I * I NT86 X . C : I n t h i s p r o g r a m , i n t86x e x e c u t e s a n I NT 2 1 H i n s t r u c t i on
* t o i n v o k e DOS s y s t em c a l l 43H ( c h a nge f i l e a t t r i b u t e s ) . T h e p r o g r a m
* u s e s i n t86x b e c a u s e t h e f i l e , wh i c h i s refe r e n c ed wi t h a fa r p o i nt e r ,
* may be i n a s e gment o t h e r t h a n t h e d e fa u l t d a t a segme n t . T h u s , t h e
* p r o g r a m mu s t e x p l i c i t l y set t h e D S reg i s t e r w i t h t h e S R E GS s t r u c t u r e .
*/

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


Iii n c l u d e <dos . h>
#i n c l u d e <stdi o . h>
#i n c l u d e < p roc e s s . h>

c h a r _fa r * f i l e n a m e = " i nt86 x . c " ;

v o i d ma i n ( )
{
u n i on RE GS · i n regs , o u t r e g s ;
s t r u c t S R E GS s e g r e g s ;
i nt res u l t ;

i n r e g s . h . a h = 0x43 ; / * DOS f u n c t i o n to c h a n ge a t t r i butes */


i n regs . h . a l = 0 ; / * S u b f u n c t i o n 0 t o get a t t r i b u t e s ) */
i n re g s . x . d x = F P_O F F C f i l e n a me > : / * D S : D X poi n t s t o f i l e n a me * /
s e g regs . d s = F P_S E G C f i l ename > :
r e s u l t = i n t86x ( 0x 2 1 , & i n re g s , &outre g s , & s e g regs > :
i f ( out regs . x . cfl a g )
p r i n t f ( " C a n ' t get f i l e a t t r i b u t e s ; e r r o r n o . % d \ n " , res u l t ) :
el se
p r i n t f ( " Att r i b s = 0x% . 4x \ n " , o u t r e g s . x . cx > :

Output

At t r i b s = 0x0020
intdos 430

Description Executes the DOS system call.

#include <dos.h>

int intdos( union REGS *inregs, union REGS *outregs );

inregs Register values on call


outregs Register values on return

Remarks The intdos function invokes the DOS system call specified by register values defined in
inregs and returns the effect of the system call in outregs. The inregs and outregs argu­
ments are unions of type REGS. The REGS type is defined in the include file DOS.H.
To invoke a system call, intdos executes an INT 2 1 H instruction. Before executing the in­
struction, the function copies the contents of inregs to the corresponding registers. After
the INT instruction returns, intdos copies the current register values to outregs. It also cop­
ies the status of the system carry flag to the cflag field in outregs. A nonzero cflag field in­
dieates the flag was set by the system call and also indicates an error condition.
The intdos function is used to invoke DOS system calls that take arguments for input or
output in registers other than DX (DH/DL) and AL. The intdos function is also used to in­
voke system calls that indicate errors by setting the carry flag. Under any other conditions,
the bdos function can be used.
Do not use the intdos function to call interrupts that modify the DS register. Instead, use
the intdosx or int86x function.

Return Value The intdos function returns the value of the AX register after the system call is completed.
If the cflag field in outregs is nonzero, an error has occurred and _doserrno is also set to
the corresponding error code.

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

t
See Also bdos, intdosx

/ * I NTDOS . C . T h i s p r o g r a m u s e s i n t d o s t o i n v o k e DOS s y s t em c a l l 2AH


* ( g ets t h c u r rent d a t e ) .
*/

/ti n c l ude < d s . h >


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

v o i d ma i n ( )
(
u n i on REGS i n regs , o u t regs ;

i n re g s . h . a h = 0x2a ; / * DOS Get D a t e func t i on : * /


i n t d o s ( & i n re g s , &outregs > :
p r i n t f ( " Da te : % d / %d / %d \ n " , o u t r e g s . h . d h , o u t r e g s . h . d l , out regs . x . cx ) ;

Output

D a t e : 6 / 1 6 / 1 989
intdosxlI 432

Description I Executes the DOS system call; accepts segment-register values.

I #include <dos.h>

int intdosx( union REGS *inregs, union REGS *outregs, struct SREGS *segregs );

inregs Register values on call

outregs Register values on return

segregs Segment-register v alues on call

Remarks The intdosx function invokes the DOS system call specified by register values defined in
inregs and returns the results of the system call in outregs. Unlike the intdos function,
intdosx accepts segment-register values in segregs, enabling programs that use large­
model data segments or far pointers to specify which segment or pointer should be used
during the system call. The REGS and SREGS types are defined in the include file DOS.H.

To invoke a system call, intdosx executes an INT 21 H instruction. Before executing the in­
struction, the function copies the contents of inregs and segregs to the corresponding regis­
ters. Only the OS and ES register values in segregs are used. After the INT instruction
returns, intdosx copies the current register values to outregs and restores OS. It also copies
the status of the system carry flag to the cflag field in outregs. A nonzero cflag field indi­
cates the flag was set by the system call and also indicates an error condition.

The intdosx function is used to invoke DOS system calls that take an argument in the ES
register or that take a OS register value different from the default data segment.

Segment values for the segregs argument can be obtained by using either the segread func­
tion or the FP_SEG macro.

Return Valu The intdosx function returns the value of the AX register after the system call is com­
pleted. If the cflag field in outregs is nonzero, an error has occurred; in such cases,
_doserrno is also set to the corresponding error code.

Campatibili � I
D ANSI • DOS D OS/2 D UNIX D XENIX

See Also bdos, FP_SEG, intdos, segread

Exampre ___,,__����-
1 * I NTDOS . C * /
Ii i n c l u d e d o s . h >
#i n c l u d e s t d i o . h >
433 intdosx

c h a r _fa r *buffer " Do l l a r - s i g n t e rmi n a ted s t r i n g \ n \ r \ n \ r $ " ;

v o i d ma i n ( )
[
u n i on REGS i n regs , o u t r e g s ;
s t ruct SREGS s eg r e g s ;

I * P r i nt a $ - t e rmi n a ted s t r i ng on t h e s c reen u s i ng DOS funct i on 0x09 . * /


i n r eg s . h . a h = 0x9 ;
i n re g s . x . dx = F P_O F F ( buffer ) ;
s e g regs . d s = FP_S E G ( buffer l ;
i n t d o s x ( & i n re g s , & o u t r eg s , & s e g regs l ;

Output

Dol l a r - s i gn t e rmi n a ted s t r i n g


is Funct ns � 434

Description I Test characters for specified conditions.

#include <ctype.h>

int isalnum( int c ) ;


int isalpha( int c ) ;
int isascii( int c ) ;
int iscntrl( int c ) ;
int isdigit( int c ) ;
int isgraph( int c ) ;
int islower( int c ) ;
int isprint( int c ) ;
int ispunct( int c ) ;
int isspace( int c ) ;
int isupper( int c ) ;
int isxdigit( int c ) ;

c Integer to be tested

Rematics Each function in the is family tests a given integer value, returning a nonzero value if the
integer satisfies the test condition and 0 if it does not. The ASCII character set is assumed.
The is functions and their test conditions are listed below:

Function Test Condition

isalnum Alphanumeric ('A'-'Z' , 'a'-'z', or ' 0 '- ' 9 ' )


isalpha Letter ('A'-'Z' or 'a'-'z')
isascii ASCII character (OxOO - Ox7F)
iscntrl Control character (OxOO - Ox IF or Ox7F)
isdigit Digit ('O'-' 9 ' )
isgraph Printable character except space (' ')
islower Lowercase letter ('a'-'z')
435 is Functions

isprint · Printable character (Ox20 - Ox7E)


ispunct Punctuation character

WJ>ace White-space character (Ox09 - OxOD or Ox20)


isupper Uppercase letter (' A'-'Z')
isxdigit Hexadecimal digit ('A'-'F','a'-'f', or '0'-'9')

The isascii routine produces meaningful results for all integer values. However, the remain­
ing routines produce a defined result only for integer values corresponding to the ASCII
character set (that is, only where isascii holds true) or for the non-ASCII value EOF (de­
fined in STDIO.H).

These routines are implemented both as functions and as macros. For details on choosing a
function or a macro implementation, see Section 1 .4, "Choosing Between Functions and
Macros."

Return Value These routines return a nonzero value if the integer satisfies the test condition and 0 if it
does not.

Compat/bl//ty isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper,
isxdigit

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

isascii

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

See Also toascii, tolower, toupper functions

Example �������-

I * I S FAM . C : T h i s p r o g r a m t e s t s a l l c h a r a ct e r s between 0x0 a n d 0x7 F ,


* t h e n d i s p l a y s e a c h c h a r a c t e r wi t h a bb r ev i a t i on s for t h e c h a r a c t e r - type
* c o d e s that a p p l y .
*I

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


#i n c l u d e < ctype . h >
I
is Functi�ns
voi dintmain<>Ich;
436

for(printch ( 0;" %ch. 2x ",0x7F;ch ; ch++


t

npri ntf(tf( """%%%c4s",3s ",", isprint(


priprintf( ch ch ' \ 0 '
<=


(

printfC " % 3s ", isalnum(


is
isascia l
)

p h a
i
)

<
( ch
ch
ch
?
;
;
;;;
) ;

nprinttr<( ""%%%3s3s3s ","",, iisi ssdgraph(


priprint cntrl(i g i t ( chchch
) ? " AN " )
) ? "A" )

;
) ? "AS" )

print� ( % 3s i s l o w er< ch
) ? "C" )
11 o n

pripri nnttr� (( "" %%%3s3s3s ",",", isiisprispspunct(acne(t( chchch


) ? )

print ;
) ? " G" )
• L•

;;
•, ) ? ) ;

npri nttfl ((( " %%3s3s ", ; isuisxpdigiper<t ( chch


priprint
) ? " PU " );
) ? "S" )
) )
II
? P R"
) u· )
n .
·
?
) ? ·
x· ) ;
" \n" )

000201
Output

AS
AS
AS
C
C
C

38393a 89
3c3d3b3e
AN AS D G PR x
AN AS D G PR x
AS G PU PR
AS G PU PR

4041423f
< AS G PU PR
= AS G PU PR
> AS G PU PR
? AS G PU PR
@ AS G PU PR
A AN A AS G PR u x
B AN A AS G PR u x
437 isatty

011St:tlpl/on Checks for a character device . .

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

int isatty( int handle );

handle Handle referring to device to be tested

Remarks The isatty function detennines whether handle is associated with a character device (a ter­
minal, console, printer, or serial port).

Return Value The isatty function returns a nonzero v alue if the device is a character device. Otherwise,
the return value is 0.

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

I* I SATTY . C : T h i s p r o g r a m c h e c k s to s e e whet h e r s t d o u t h a s been


* r e d i rected to a f i l e .
*I

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


//i n c l u d e < i o . h >

v o i d ma i n ( )
(
i f ( i s a tty ( f i l eno C s t d o u t ) ) )
p r i n t f ( " s tdout h a s not been red i rected t o a f i l e \ n " ) ;
el se
p r i n t f ( " s t dout h a s been red i rected t o a f i l e \ n " l ;

Output

s t d o u t ha s not been red i rected to a f i l e


itaa 438

Description Converts an integer to a string.

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

char *itoa( int value, char *string, int radix );

value Number to be converted

string String result

radix Base of value

Remarks The itoa function converts the digits of the given value argument to a null-terminated char­

-�-· II
acter string and stores the result (up to 17 bytes) in string. The radix argument specifies the
base of value; it must be in the range 2-36. If radix equals 10 and value is negative, the
first character of the stored string is the minus sign (-).

The itoa function returns a pointer to string. There is no error return.

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

I
See Also ltoa, ultoa

Exampm ����������������������������
I * I TOA . C : 1 h i s p r o g r a m c o n v e r t s i n t e g e r s of v a r i ous s i z e s to s t r i n g s

J,
* in vari o s radi xes .
*/

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

: :: :::
oi i

� h e r [ 20 ] ;
i nt i = 344 5 ;
l ong 1 = - 344 1 1 5 L ;
unsi gned 1 on g u l = 1 2 34 5 6 7 8 90 U L ;
1

I
'

!
01 Uoa

i t oa < i , b u f fe r , 1 0 ) ;
pri ntf ( " St r i n g o f i n t e g e r %d < ra d i x 10 ) : % s \ n " , i , b u f f e r ) ;
i t oa ( i , b u f fe r , 1 6 ) ;
pri ntf( " St r i n g o f i nt e g e r %d < ra d i x 1 6 ) : 0x% s \ n " , i , buffer ) ;
i t oa ( i , buffe r , 2 ) ;
pri ntf ( " St r i n g of i nt e g e r %d < ra d i x 2 ) : % s \ n " , i , b u f f e r ) ;

l t o a ( 1 , b u f fe r , 1 6 ) ;
p r i n t f ( " St r i n g o f l on g i n t %l d ( ra d i x 1 6 ) : 0x%s \ n " , 1 , buffer ) ;

u l t o a ( u l , b u f fe r , 1 6 > ;
p r i n t f ( " St r i n g o f u n s i g n ed l on g % l u < ra d i x 1 6 ) : 0x%s \ n " , u l , b u f f e r ) ;

Output

Stri ng of i n t e g e r 3445 < ra d i x 1 0 ) : 3445


Stri ng of i n t e g e r 3445 ( ra d i x 1 6 ) : 0xd 7 5
Stri ng of i n t e g e r 3445 ( ra d i x 2 ) : 1 1 0 1 0 1 1 1 0 1 0 1
Stri ng of l on g i nt - 344 1 1 5 < ra d i x 1 6 ) : 0x fffabfcd
Stri ng of u n s i gned l on g 1 234567890 ( ra d i x 1 6 ) : 0x499602d2
kbhit 440

DIJICl'lpllon Checks the console for keyboard input.

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

int kbhit( void );

Remades The kbhit function checks the console for a recent keystroke. If the function returns a non­
zero value,_ a keystroke is waiting in the buffer. The program can then call getch or getche
to get the keystroke.

R1tum Valu1 The kbhit function returns a nonzero value if a key has been pressed. Otherwise, it re­
turns O.

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

I* KBH I T . C : T h i s p r o g r a m l oops u n t i l t h e u s e r p res s e s a key .


* I f k bh i t r e t u r n s n o n z e r o , a k ey s t ro k e i s wa i t i n g i n t h e buffe r .

I
* T h e p r o g a m c a n c a l l g e t c h o r getc h e t o get t h e key s t ro k e .
*I

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


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

v o i d ma i n ( )
{
I * D i s p l y mes s a g e u nt i l k ey i s p r e s s e d . * /
whi l e( ! bhi t ( ) )
c p u t s " H i t me ! ! • ) ;

I * U s e g t c h to t h row k ey away . * /
p r i n t f ( \ n Key s t r u c k wa s ' %c ' \ n " , get c h ( ) > :
getch ( ) ;

Output I
l
H i t me ! ! H i me ! ! H i t me ! ! H i t me ! ! H i t me ! ! H i t me ! ! H i t me ! !
Key s t r u c k a s ' k '
441 labs

DBBcrlptlon Calculates the absolute value of a long integer.

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

#include <math.h>

long labs( long n ) ;

n Long-integer value

Remarks The labs function produces the absolute value of its long-integer argument n.

Return value The labs function returns the absolute value of its argument. There is no error return.

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

See Also abs, cabs, fabs

I * ABS . C : T h i s prog r a m c omputes a n d d i spl a y s t h e a b s o l u t e v a l ues of


* s e v e ra l n umb e r s .
*I

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


#i n c l ude <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 i x = -4 , i y ;
l ong l x = -41567 L , l y ;
doubl e dx = - 3 . 1 4 1 5 9 3 , dy ;

iy = abs ( i x ) ;
p r i n t f ( " T h e a b s o l u t e va l u e of %d i s %d \ n " , i x , i y ) ;

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

dy = f a b s ( dx ) ;
p r i ntf ( " T h e a b s o l u t e v a l ue of %f i s % f \ n " , dx , dy ) ;
labs 442

Output

T h e a b s o l u t e v a l u e of - 4 i s 4
T h e a bs o l u t e v a l u e of - 4 1 5 6 7 i s 4 1 5 6 7
T h e a bs o l u t e v a l u e of - 3 . 1 4 1 5 9 3 i s 3 . 1 4 1 5 9 3
443 ldexp, ldexpl

Description Compute a real number from the mantissa and exponent.

#include <math.h>

double ldexp( double x, int exp );


long double ldexpl( long double x, int exp );

x Floating-point value
exp Integer exponent

Remarks The ldexp and ldexpl functions calculate the value of x * 2exp.

Return Value The ldexp and ldexpl functions return x * 2exp. If an overflow results, the functions return
± HUGE_VAL (depending on the sign of x) and set errno to ERANGE.
The ldexpl function uses 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.

Compat/bHity Idexp

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

ldexpl

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

See Also frexp, modf

Exampm ��������-

1* LDEX P . C */
#i n c l ude <ma t h . h >
#i n c l ude < s t d i o . h >
ldexp, l exp/ 444

v o i d ma i n ( )
{
doubl e x = 4.0, y;
i nt p = :

y = l d ex ( x , p > :
p r i n t f { %2 . l f t i mes two t o t h e powe r of %d i s %2 . l f \ n " , x , p , y >:

Output

4 . 0 t i mes t o the powe r of 3 i s 3 2 . 0


445 /div

DllSt:rlptlan Computes the quotient and remainder of a long integer.

#include <Stdlib.h>

ldiv_t ldiv ( long int numer, long int denom ) ;

numer Numerator
denom Denominator

Remarks The ldiv function divides numer by denom, computing the quotient and the 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.

The ldiv function is similar to the div function, with the difference being that the argu­
ments and the members of the returned structure are all of type long int.

The ldiv_t structure, defined in STDLIB.H, contains the following elements:

Element Description

long int quot Quotient

long int rem Remainder

Return Value The ldiv function returns a structure of type ldiv_t, comprising both the quotient and the
remainder.

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

S11 A/sa div

I * LD I V . C : T h i s p r o g r a m t a kes two l on g i nt e g e r s a s comma n d - l i n e


* a rg umen t s a n d d i s p l a y s t h e r e s u l t s o f t h e i n t e g e r d i v i s i on .
*I

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

v o i d ma i n ( )
(
l ong x = 5 149627 , y = 2 3487 9 ;
l d i v_t d i v_r e s u l t ;

d i v_res u l t = l di v C x , y ) ;
p r i n t f C F o r %l d I % l d , t h e q u o t i ent i s % l d , a nd t h e rema i n d e r i s % l d \ n " ,
, y , d i v_r e s u l t . q uot , d i v_re s u l t . rem ) ;

Output

For 5149627 2 3487 9 , t h e q u ot i ent i s 2 1 , a n d t h e rema i n d e r i s 2 1 7 1 68


447 /find

DllBl:l'lpllan Perfonns a linear search for the specified key.

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


char *lf'md( const void *key, const void *base, unsigned int *num, unsigned int width,
int ( *compare )( const void *eleml, const void *elem2 ) );

key Object to search for

base Pointer to base of search data


num Number of array elements
width Width of array elements
compare( ) Pointer to comparison routine
elem] Pointer to the key for the search

e/em2 Pointer to the array element to be compared with the key

Remarks The lfind function perfonns a linear search for the value key in an array of num elements;
each element is width bytes in size. (Unlike bsearch, lfind does not require the array to be
sorted.) The base argument is a pointer to the base of the array to be searched.

The compare argument is a pointer to a user-supplied routine that compares two array ele­
ments and then returns a value specifying their relationship. The lfind function c alls the
compare routine one or more times during the search, passing pointers to two array ele­
ments on each call. This routine must compare the elements, then return one of the follow­
ing values:

Value Meaning

Nonzero Elements are different


0 Elements are identical

Return Value If the key is found, lfind returns a pointer to the element of the array at base that matches
key. If the key is not found, lfind returns NULL.

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


/find 448

Ses A/sa bsearch, lsearch, qsort

Exampm ��+-�������-
j ..

I * L F I N D . C : � h i s p r o g r a m u s e s l f i nd t o sea r c h f o r t h e word " h el l o "


* i n t h e c o ma n d - l i n e a rgumen t s .
*/

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

�oi d �
i n t c ompa re ( c h a r **a rg l , c h a r * * a r g 2 > :

ma i n ( i t a rgc , c h a r * * a r g v >

j
c h a r **resul t ;
c h a r * k.ey " h el l o " ;

resul t = c h a r ** ) l f i nd ( ( c h a r * > & k ey , < c h a r * ) a rg v ,


&a rgc , s i zeof ( c h a r * ) , c ompa re > :
i f ( resul )
p r i n t f ( " % s found \ n " , * r e s u l t > :
el se
p r i n t f ( " h e l l o n o t found ! \ n " > :

r
i nt c ompa re ( a r ** a rg l , c h a r **a rg2
(
1
r e t u r n ( s r cmp1 C *a r g l , *a rg2 ) > :

Output

[ C : \ L I B R E F ] l f i nd W h a t i f I s a i d H e l l o worl d
H e l l o found
449 _lineto Functions

DISCl'/ptlan Draw lines to specified points.

#include <graph.h>

short _far _lineto( short x, short y );


short _far _lineto_w( double wx, double wy );

x, y End point
wx, wy End point

R1matlcs The functions in the _lineto family draw a line from the current graphics position up to
and including the destination point. The destination point for the _lineto function is given
by the view-coordinate point (x, y). The destination point for the _lineto_w function is
given by the window-coordinate point (wx, wy).
The line is drawn using the current color, logical write mode, and line style. If no error
occurs, _lineto sets the current graphics position to the view-coordinate point (x, y);
_lineto_w sets the current position to the window-coordinate point (wx, wy).
If you use _floodfill to fill in a closed figure drawn with _lineto calls, the figure must be
drawn with a solid line-style pattern.

R1tum Value The _lineto and _lineto_w routines return a nonzero value if anything is drawn; otherwise,
they return 0.

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

81e A/sa _getcurrentposition functions, _moveto functions, _setlinestyle

I * MOV ETO . C : T h i s p r o g r a m d r aws l i n e s egme n t s o f d i fferent c o l o r s . * /

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


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

v o i d ma. i n ( )
(
s h o rt x , , x i nc , y i n c , c o l o r .. 1 ;
s t ruct v i e o c o n f i g v ;

I * Fi nd a v a l i d g ra p h i c s mode . * I
i f ( ! _s e t i d eomod e ( _MAXCO LORMODE ) )
exi t C >;
_getv i d eo onfi g ( &v > :
x i nc = v . umx p i x e l s I 50 ;
yi nc - v . umyp i x e l s I 50 ;

f o r ( x .. , y .. v . n umyp i xel s - 1 ; x < v . n umxp i xel s ; x += x i n c , y -- y i n c )


(
_s e t c o l o r C c o l o r++ % 1 6 > :
_mov e t ( x , 0 ) ;
_l i n et c 0 , y > ;

t
)
getch C > :

_s etv i d e o d e C _D E FAU LTMODE ) ;


451 localeconv

Description Gets detailed infonnation on locale settings.

#include <locale.h>

struct lconv *localeconv( void );

Remarks The localeconv function gets detailed infonnation on the locale-specific settings for
numeric fonnatting of the program's current locale. This infonnation is stored in a struc­
ture of type lconv.
The lconv structure, defined in LOCALE.H, contains the following elements:

Element Description

char *decimal_point Decimal-point character for nonmonetary


quantities.
char *thousands_sep Character used to separate groups of digits
to the left of the decimal point for non­
monetary quantities.
char *grouping Size of each group of digits in non­
monetary quantities.
char *int_curr_symbol International currency symbol for the cur­
rent locale. The first three characters
specify the alphabetic international cur­
rency symbol as defined in the ISO 421 7
Codes for the Representation of Currency
and Funds standard. The fourth character
(immediately preceding the null character)
is used to separate the international cur­
rency symbol from the monetary quantity.
char *currency_symbol Local currency symbol for the current
locale.
char *mon_decimal_point Decimal-point character for monetary
quantities.
char *mon_thousands_sep Separator for groups of digits to the left of
the decimal place in monetary quantities.
char *mon_grouping Size of each group of digits in monetary
quantities.
char *positive_sign String denoting sign for nonnegative
monetary quantities.
lacalecan 452

char *negative_sign String denoting sign for negative monetary


quantities.
char int_frac_digits Number of digits to the right of the deci­
mal point in internationally formatted
monetary quantities.
char frac_digits Number of digits to the right of the deci­
mal point in fonnatted monetary
quantities.
char p_cs_precedes Set to 1 if the currency symbol precedes
the value for a nonnegative formatted
monetary quantity. Set to 0 if the symbol
follows the value.
char p_sep_by_space Set to 1 if the currency symbol is sepa­
rated by a space from the value for a non­
negative formatted monetary quantity. Set
to 0 if there is no space separation.
char n_cs_precedes Set to 1 if the currency symbol precedes
the value for a negative fonnatted
monetary quantity. Set to 0 if the symbol
succeeds the value.
char n_sep_by_space Set to 1 if the currency symbol is sepa­
rated by a space from the value for a nega­
tive fonnatted monetary quantity. Set to 0
if there is no space separation.
char p_sign_posn Position of positive sign in nonnegative
fonnatted monetary quantities.
char n_sign_posn Position of positive sign in negative for­
matted monetary quantities.
453 localeconv

The elements of grouping and mon_grouping are interpreted according to the following
rules:
Value Interpretation
CHAR_MAX No further grouping is to be performed.
0 The previous element is to be repeatedly used for the re­
mainder of the digits.
n The integer value n is the number of digits that make up the
current group. The next element is examined to determine the
size of the next group of digits before the current group.

The values for p_sign_posn and n_sign_posn are interpreted according to the following
rules:
Value Interpretation

Parentheses surround the quantity and currency symbol


Sign string precedes the quantity and currency symbol
Sign string follows the quantity and currency symbol
Sign string immediately precedes the currency symbol
Sign string immediately follows the currency symbol

Return Value The localeconv function returns a pointer to a structure of lconv type. Calls to the
setlocale function with category values of LC_ALL, LC_MONETARY, or
LC_NUMERIC will overwrite the contents of the structure.

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

S11 Alsa setlocale, strcoll, strftime, strxfrm


localtim 454

Description Converts a time value and corrects for the local time zone.

#include <time.h>

struct tm "'localtime( const time_t *timer );

timer Pointer to stored time

structure of type tm. The long value timer represents the seconds elapsed since 00:00:00,
Remarks The localtime function converts a time stored as a time t value and stores the result in a

January l , 1 970, Greenwich mean time; this value is usually obtained from the time
function.
The fields of the structure type tm store the following values:

Element Value Stored

int tm_sec Seconds


int tm_min Minutes
int tm_hour Hours (0-24)
int tm_mday Day of month ( 1-3 1 )
int tm_mon Month (0 -1 1 ; January = 0)
int tmJear Year (current year minus 1 900)
int tm_wday Day of week (0- 6; Sunday = 0)
int tmJday Day of year (0 -365; January 1 = 0)
int tm_isdst Nonzero if daylight saving time is in effect, otherwise 0

Note that the gmtime, mktime, and localtime functions use a single statically allocated
tm structure for the conversion. Each call to one of these routines destroys the result of the
previous call.
The localtime function makes corrections for the local time zone if the user first sets the
environment variable TZ. When TZ is set, three other environment variables (timezone,
daylight, and tzname) are automatically set as well. See tzset for a description of these
variables.
The TZ variable is not part of the ANSI standard definition of localtime but is a Microsoft
extension.
455 locallime

Rlllum Value The localtime function returns a pointer to the structure result. DOS and OS/2 do not ac­
commodate dates prior to 1 980. If the value in timer represents a date prior to January 1 ,
1 980, the function returns NULL.

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

S11 A/10 asctime, ctime, ftime, gmtime, time, tzset

I * LOCALTI M . C : T h i s p r o g r a m u s e s t i me t o get t h e c u rrent t i me a n d


* t h e n u s e s l oc a l t i me t o c o n v e r t t h i s t i me to a s t ru c t u r e r e p r e s en t i n g
* t h e l oc a l t i me . T h e p r o g r a m c o n v e r t s t h e r e s u l t from a 24 - h o u r c l o c k
* t o a 1 2 - h o u r c l o c k a n d d e t e rmi n e s t h e p r o p e r exten s i on C AM o r PM ) .
*/

#i n c l u d e < s t d i o . h >
#i n c l u d e < s t r i n g . h >
#i n c l ud e < t i me . h >

v o i d ma i n ( )
(
s t r u c t tm * n ewt i me ;
c h a r a m_pm [ ] = " AM " :
t i me_t l on g_t i me ;

t i me ( & l o n g_t i me > : / * Get t i me a s l on g i n tege r . * /


n ewt i me = l oc a l t i me ( & l ong_t i me > : / * C o n v e r t t o l oc a l t i me . * /

i f ( newt i me - > tm_h o u r < 1 2 / * S e t up exten s i on . * /


s t rc py ( a m_pm , " AM " ) ;
i f ( n ewt i me - > tm_h o u r > 1 2 / * C o n v e r t f rom 24 - h o u r * /
n ewt i me - > tm_h o u r -=1 2 ; /* t o 1 2 - h o u r c l oc k . * /

p r i ntf ( " % . 1 9 s % s \ n " , a s c t i me ( n ewt i me ) , a m_pm > :

Output

F r i J u n 1 6 06 : 2 7 : 02 AM
locking 456

Dat:rlptian Locks or unlocks bytes of a file.

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

int locking( int handle, int mode, long nbytes );

handle File handle


mode File-locking mode
nbytes Number of bytes to lock

Remarks The locking function locks or unlocks nbytes bytes of the file specified by handle. Lock­
ing bytes in a file prevents access to those bytes by other processes. All locking or unlock­
ing begins at the current position of the file pointer and proceeds for the next nbytes bytes.
It is possible to lock bytes past the end of the file.
The mode argument specifies the locking action to be performed. It must be one of the fol­
lowing manifest constants:

Constant Action

LK_LOCK Locks the specified bytes. If the bytes cannot be locked, imme­
diately tries again after 1 second. If, after IO attempts, the
bytes cannot be locked, returns an error.
LK NBLCK Locks the specified bytes. If bytes cannot be locked, returns
an error.
LK_NBRLCK Same as LK_NBLCK.
LK_RLCK Same as LK_LOCK.
LK_UNLCK Unlocks the specified bytes. (The bytes must have been pre­
viously locked.)

More than one region of a file can be locked, but no overlapping regions are allowed.
When a region of a file is being unlocked, it must correspond to a region that was pre­
viously locked. The locking function does not merge adjacent regions; if two locked re­
gions are adjacent, each region must be unlocked separately.
Regions should be locked only briefly and should be unlocked before closing a file or exit­
ing the program.
467 locking

The locking function should be used only under OS/2 or under DOS versions 3.0 and later;
it has no effect under earlier versions of DOS. Also, file sharing must be loaded to use the
locking function. Note that under DOS versions 3.0 and 3. 1 , the files locked by parent
processes may become unlocked when child processes exit.

Retum Value The locking function returns 0 if successful. A return value of -1 indicates failure, and
ermo is set to one of the following values:

Value Meaning

EACCES Locking violation (file already locked or unlocked).


EBADF Invalid file handle.
EDEADLOCK Locking violation. This is returned when the LK_LOCK or
LK_RLCK flag is specified and the file cannot be locked after
10 attempts.

EINVAL An invalid argument was given to the function.

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

See A/so creat, open

I * LOCKI NG . C : T h i s p r o g r a m opens a f i l e wi t h s h a r i n g . I t l oc k s s ome


* bytes before rea d i ng t h em , t h e n u n l o c k s t h em . N ote t h a t t h e p r o g r a m
* w o r k s c o r re ct l y on l y i f t h e fol l owi ng con d i t i ons a re met :
* -T h e f i l e exi s t s
* -T h e p r o g r a m i s r u n u n d e r OS / 2 , u n d e r DOS 3 . 0 o r l a t e r
*
wi t h f i l e s h a r i n g i n s t a l l ed ( SHARE . C OM o r SHA R E . E X E ) , o r
*
i f a M i c rosoft N etwo rks c ompa t i bl e n etwo r k i s run n i n g
*I

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


#i n c l u d e < sy s \ types . h >
#i n c l u d e < sy s \ s ta t . h >
#i n c l u d e < s y s \ l oc k i ng . h >
#i n c l ude < s h a re . h >
#i n c l u d e <fcntl . h>
#i n c l u d e <stdi o . h>
#i n c l u d e <stdl i b . h>
locking 458

v o i d ma i n ( )
(
i n t f h , n umrea d ;
l ong pos r e s u l t ;
c h a r buf e r [ 4 0 ] ;

f h = s op n C " l oc k i n g . c " , O_RDW R , SH_D E NY N O , S_I READ I S_I W R I T E ) ;


I * Q u i t f c a n ' t open f i l e o r DOS v e rs i on d o e s n ' t s up p o rt s h a r i n g . * /

i f ( ( fh - l l 1 1 ( _o s ma j o r < 3 ) )
exi t C 1 > ;

l
I * Loc k ome byt e s a n d read t h em . Then u n l o c k . * /
i f ( l oc k n g ( f h , L K_N B LC K , 3 0 L ) ! = - 1 )
(
pri nt C " N o o n e c a n c h a n g e t h e s e by t e s w h i l e I ' m rea d i n g t h em\ n " ) ;
n umre d - rea d ( f h , buffe r , 30 ) ;
pri nt C " %d byt e s read : % . 30s \ n " , numrea d , buffer ) ;
l oc k i g ( fh , L K_U N LC K , 3 0 L ) ;

l
pri nt C " N ow I ' m d o n e . Do w h a t you w i l l wi t h t h em\ n " l ;
}

: e r ro
el s
C " Loc k i n g fa i l ed \ n " ) ;

cl ose( f );

�e lr
c a n h a n g e t h e s e bytes w h i l e I ' m •ea d i n g t h em
30 byt e s rea d : / * LOC K I N G . C : T h i s p ro g r a m ope
N ow I ' • d o n . Do what y o u wi l l wi t h t h em

I
I
459 log Functions

DBScrlpllan Calculate logarithms.

#include <math.h>

double log( double x );


double loglO( double x );
long double logl( long double x ) ;

long double loglOI( long double x ) ;

x Value whose logarithm is to be found

Remarks The log and loglO functions calculate the natural logarithm and the base- 10 logarithm, re­
spectively, of x. The logl and loglOl 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.

Return Value The log functions return the logarithm of the argument x. If x is negative, the functions
print a DOMAIN error message to stderr, return the value -HUGE_VAL, and set errno to
EDOM. If x is 0, the functions print a SING error message to stderr, return the value
-HUGE_VAL, and set errno to ERANGE.
Error handling can be modified by using the matherr or _matherrl routine.

Campallbl/lty log, loglO

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

logl, loglOl

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

See Also exp, matherr, pow functions

I * LOG . C : T h i s p r o g r a m u s e s l og a n d l o g 1 0 to c a l c u l a t e t h e n a t u r a l
* l o g a r i t hm a n d t h e ba s e - 1 0 l og a r i thm of 9 , 000 .
*I

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


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

�1
v o i d ma i n ( )
{ !
doubl e x 9000 . 0 ;
doubl e y ;

y = l og ( � > :
p r i ntf ( " l o g ( % . 2 f ) = %f\ n " , x , y > :
y = l og10 ( x ) ;
pri ntf( " l og10( % . 2f J = %f\n " , x, y J ;

I
Output

i! =
l o g ( 9000 . 00 1 = 9 . 1 04980
l og 1 0 ( 9000 . 0 J 3 . 954243

I
461 long double Functions

The 8087 family of numeric coprocessor chips supports the 80-bit precision floating-point
data type. In Microsoft C, version 6.0, the long double functions, whose names end with 1,
map the C long double type into this 80-bit, 10-byte form. Unlike the regular floating­
point functions (such as acos), which return values of type double, these long double func­
tions (such as acosl) return values of type long double. The long double functions also
return their values on the coprocessor stack for all calling conventions.
The long double type is also supported by the addition of the "L" prefix for a floating­
point format specification in the printf and scanf family of functions.
The long double versions are described on the reference pages for their regular counter­
parts. These are the regular C run-time math functions with corresponding long double
equivalents:
Regular Function Long Double Form

acos acosl
asin asinl
atan atanl
atan2 atan21
atof atold
cabs cabsl
ceil ceill
cos cosl
cosh coshi
exp expI
fabs fabsl
floor floorI
fmod fmodl
frexp frexpl
hypot hypotl
Idexp ldexpl
log logl
loglO loglOI
matherr matherrl
modf modfl
long do le Functions 462

pow powI
sin sinl

sinh sinhl

sqrt sqrtl

tan tanl

tanh tan hi
463 longjmp

Description Restores stack environment and execution locale.

#include <Setjmp.h>

void longjmp( jmp_buf env, int value );

env Variable in which environment is stored


value Value to be returned to setjmp call

Remarks The longjmp function restores a stack environment and execution locale previously saved
in env by setjmp. The setjmp and longjmp functions provide a way to execute a nonlocal
goto; they are typically used to pass execution control to error handling or recovery code
in a previously called routine without using the normal call and return conventions.
A call to setjmp causes the current stack environment to be saved in env. A subsequent
call to longjmp restores the saved environment and returns control to the point immedi­
ately following the corresponding setjmp call. Execution resumes as if value had just been
returned by the setjmp call. The values of all variables (except register variables) that are
accessible to the routine receiving control contain the values they had when longjmp was
called. The values of register variables are unpredictable.
The longjmp function must be called before the function that called setjmp returns. If
longjmp is called after the function calling setjmp returns, unpredictable program be­
havior results.
The value returned by setjmp must be nonzero. If value is passed as 0, the value l is substi­
tuted in the actual return.
Observe the following three restrictions when using longjmp:

1 . Do not assume that the values of the register variables will remain the same. The values
of register variables in the routine calling setjmp may not be restored to the proper
values after longjmp is executed
2. Do not use longjmp to transfer control from within one overlay to within another. The
overlay manager keeps the overlay in memory after a call to longjmp.
3. Do not use longjmp to transfer control out of an interrupt-handling routine unless the
interrupt is caused by a floating-point exception. In this case, a program may return
from an interrupt handler via longjmp if it first reinitializes the floating-point math
package by calling _fpreset.

Return Value None.


464

tf
I

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

See Also setjmp

Example See the example for _fpreset.


465 _/rot/, _lrotr

Description Rotate bits to the left (_lrotl) or right (_lrotr).

#include <Stdlib.h>

unsigned long _lrotl( unsigned long value, int shift );


unsigned long _lrotr( unsigned long value, int shift );

value Value to be rotated


shift Number of bits to shift

Remarks The _lrotl and _lrotr functions rotate value by shift bits. The _lrotl function rotates the
value left. The _lrotr function rotates the value right. Both functions "wrap" bits rotated
off one end of value to the other end.

Return Value Both functions return the rotated value. There is no error return.

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

See Also _rotl, _rotr

I * L ROT . C * /
#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 ( )
(
u n s i gned l on g v a l = 0x0fa c3 5 7 9 1 ;

p r i n t f ( " 0x%8 . 8l x r o t a t e d l e ft e i g h t t i mes i s 0x%8 . 8 l x \ n " ,


v a 1 , _ l rot l C v a 1 , 8 ) );
p r i n t f ( " 0x%8 . 8l x rota ted r i g h t f o u r t i mes i s 0x%8 . 8l x \ n " ,
v a l , _l rot r ( v a l , 4 ) );

Output

0xfa c 3 5 7 9 1 r o t a t e d l eft e i g h t t i me s i s 0xc 3 5 7 9 1 fa


0xfa c 3 5 7 9 1 r o t a t e d r i g h t fo u r t i me s i s 0 x l f a c 3 5 7 9
/search 466

Oest:rlpllan Performs a linear search for a value; adds to end of list if not found.

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

char *Isearch( const void *key, const void *base, unsigned int *num,
unsigned int width, int ( *compare )( const void *elem], const void *elem2 ) ) ;

key Object to search for


base Pointer to base of search data
num Number of elements
width Width of elements
compare Pointer to comparison routine
elem] Pointer to the key for the search
elem2 Pointer to the array element to be compared with the key

Rematlrs The lsearch function performs a linear search for the value key in an array of num ele­
ments, each of width bytes in size. (Unlike bsearch, lsearch does not require the array to
be sorted.) The base argument is a pointer to the base of the array to be searched.
If key is not found, lsearch adds it to the end of the array.
The compare argument is a pointer to a user-supplied routine that compares two array ele­
ments and returns a value specifying their relationship. The lsearch function calls the
compare routine one or more times during the search, passing pointers to two array ele­
ments on each call. This routine must compare the elements, then return one of the follow­
ing values:

Value Meaning

Nonzero Elements are different


0 Elements are identical

Retum Value If the key is found, lsearch returns a pointer to the element of the array at base that
matches key. If the key is not found, lsearch returns a pointer to the newly added item at
the end of the array.
467 /search

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

See Also bsearch, Hind

Example See the example for Hind.


/seek 468

Description Moves a file pointer to the specified location.

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


#include <Stdio.h>

long lseek( int handle, long offset, int origin );

handle Handle referring to open file


offset Number of bytes from origin
origin Initial position

Remarks The lseek function moves the file pointer associated with handle to a new location that is
offset bytes from origin. The next operation on the file occurs at the new location. The
origin argument must be one of the following constants, which are defined in STDIO.H:

Definition

SEEK_SET Beginning of file


SEEK_CUR Current position of file pointer
SEEK_END End of file

The lseek 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
before the beginning of the file causes an error.

Return Value ! The lseek function returns the offset, in bytes, of the new position from the beginning of
the file. The function returns -1 L to indicate an error and sets errno to one of the follow­
ing values:

Value Meaning
EBADF Invalid file handle
EINVAL Invalid value for origin, or position specified by offset is
before the beginning of the file

On devices incapable of seeking (such as terminals and printers), the return value is
undefined.
469 /seek

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

SBB AIBO fseek, tell

I * L S E EK . C : T h i s p r o g r a m f i r s t opens a f i l e n a med L S E E K . C .
* I t t h e n u s e s l s e e k t o f i n d t h e be g i n n i n g of t h e f i l e ,
* t o f i nd t h e c u r rent pos i t i on i n t h e f i l e , a n d t o f i nd
* the end o f the f i l e .
*I

I/i n c l u d e < i o . h>


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

v o i d ma i n ( )
(
i nt f h ;
l on g pos ; I * Pos i t i on of f i l e p o i n t e r * /
c h a r buffer [ 1 0 ] ;

f h = open ( " l s e e k . c " , O_RDON LY ) ;

/ * Seek t h e beg i n n i n g o f t h e f i l e : * /
pos = l s ee k C f h , 0 L , S E E K_S ET ) ;
i f ( pos = ll >
-

p e r ro r C " l s e e k t o beg i n n i ng fa i l ed " ) ;


el se
p r i n t f C " P o s i t i on f o r begi n n i n g o f fi l e s e e k = % l d \ n " , pos ) ;

/ * Move f i l e po i n t e r a l i tt l e * /
rea d ( f h , buffe r , 1 0 ) ;

I * Fi nd c u r re n t pos i t i on : * /
pos = l s e e k C f h , 0 L , S E E K_CU R ) ;
i f ( pos == - l l >
p e r ro r C � l s e e k t o c u r rent pos i t i on fa i l ed " ) ;
el se
p r i n t f C " Po s i t i on f o r c u r rent po s i t i on s e e k = % l d \ n " , p o s > :
/seek 470

I * S e t h e e n d of t h e f i l e : * /
p o s = l e e k ( f h , 0 L , S E E K_E N D ) ;
i f ( p o s == - l l >
p e r r J r ( " l s e e k to e n d fa i l e d " > ;
el se
p r i n � f ( " P o s i t i o n f o r e n d of f i l e s e e k = % l d \ n " , p o s ) ;

cl ose ( );

r
I

I
Output
I
Pos i t i on f b e g i n n i n g of f i l e s e e k = 0
P os i t i on fr r c u r r e n t p o s i t i on s e e k = 1 0
P o s i t i o n fq r e n d of f i l e s e e k = 1 1 83
411 ltoa

D11St:r/pllan Converts a long integer to a string.

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

char *Itoa( long value, char *string, int radix );

value Number to be converted


string String result
radix Base of value

Rematks The lt0a function converts the digits of value to a null-tenninated character string and
stores the result (up to 33 bytes) in string. The radix argument specifies the base of value,
which must be in the range 2-36. If radix equals 10 and value is negative, the first charac­
ter of the stored string is the minus sign (-).

Return Value The Itoa function returns a pointer to string. There is no error return.

Campalibllily 0 ANSI • D.OS • OS/2 0 UNIX 0 XENIX

See Also itoa, ultoa

I * I TOA . C : T h i s p rog r a m c o n v e r t s i n t e g e r s of v a r i ous s i z e s t o s t r i n g s


* i n v a r i o u s r a d i xes .
*I

#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 buffe r [ 20 ] ;
i nt i = 344 5 ;
l on g 1 = - 344 1 1 5 L ;
u n s i g n ed l on g u l = 1 2 3 4 5 6 7890U L ;
lloa 472

i toa C i , buffe r , 1 1/J ) ;


printfC S t r i ng of i n t e g e r %d ( ra d i x 11/J ) : % s \ n " , i , buffer ) ;
i toa C i , buffe r , 1 6 ) ;
p r i ntf C St r i ng o f i n t e g e r %d ( ra d i x 1 6 ) : l/Jx%s \ n " , i , buffer ) ;
i toa C i , buffe r , 2 ) ;
pri ntfC S t r i ng of i n t e g e r % d ( ra d i x 2 ) : % s \ n " , i buffer ) ;

!
l t oa C l , buffer , 1 6 > :
p r i n t f ( S t r i ng of l on g i n t % l d < ra d i x 1 6 ) : l/Jx% s \ n " , l , buffer ) ;

u l toa C u ll ,buffe r , 1 6 ) ;
p r i ntf ( " St r i ng o f u n s i gned l on g % l u ( ra d i x 1 6 ) : l/Jx% s \ n " , u l , buffer ) ;

Output

St r i n g of teger 3445 ( ra d i x 1 1/J l : 3445


Stri ng of t e g e r 3445 ( r a d i x 1 6 ) : l/J x d 7 5
Stri ng of teger 3445 < ra d i x 2 ) : 1 1 1/J l l/J l l l l/J i lll l
St r i n g of 1 ng i nt - 3 44 1 1 5 ( ra d i x 1 6 ) : l/Jxfffabfcd
Stri ng of u s i gned l on g 1 2 345 67891/J ( ra d i x 1 6 ) : l/Jx49961/J2d2
473 _makepath

Description Creates a single path name.

#include <Stdlib.h>

void _makepath( char *path, char *drive, char *dir, char *fname, char *ext );

path Full path-name buffer


drive Drive letter
dir Directory path
jname File name
ext File extension

Remarks The _makepath routine creates a single path name, composed of a drive letter, directory
path, file name, and file-name extension. The path argument should point to an empty buff­
er large enough to hold the complete path name. The constant _MAX_PATH, defined in
STDLIB.H, specifies the maximum size path that the _makepath function can handle.
The other arguments point to buffers containing the path-name elements:

Buffer Description

drive The drive argument contains a letter (A, B, etc.) correspond­


ing to the desired drive and an optional trailing colon. The
_makepath routine will insert the colon automatically in the
composite path name if it is missing. If drive is a null char­
acter or an empty string, no drive letter and colon will appear
in the composite path string.
dir The dir argument contains the path of directories, not includ­
ing the drive designator or the actual file name. The trailing
slash is optional, and either forward slashes ( I ) or
backslashes ( \) or both may be used in a single dir argument.
If a trailing slash ( I or \ ) is not specified, it will be inserted
automatically. If dir is a null character or an empty string, no
slash is inserted in the composite path string.
_makep th 474

jname The jname argument contains the base file name without any
extensions. Ifjname is NULL or points to an empty string, no
file name is inserted in the composite path string.
ext The ext argument contains the actual file-name extension,
with or without a leading period (.). The _makepath routine
will insert the period automatically if it does not appear in ext.
If ext is a null character or an empty string, no period is in­
serted in the composite path string.

There are no size limits on any of the above four fields. However, the composite path must
be no larger than the _MAX_PATH constant. The _MAX_PATH limit permits a path name
much larger than any of the current versions of DOS or OS/2 will handle.

Return Value None.

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

See A/sa _fullpath, _splitpath

Examp• ---+---
1 * MAKE PATH . C * /
#i nc l ude < s d l i b . h>
#i n c l u d e < s d i o . h >

v o i d ma i n ( )
(
cha r pat _b u f f e r [_MAX_PATH l ;
char dri e [_MAX_D R I V E ] ;
cha r
char
di r
fna
� _MAX_D I R ] ;
e [_MAX_FNAM E ] ;
cha r ext _MA X_E X T ] ;
I[
.
_ma k e p a t C p a t h_b u f f e r , " c " , " \ \ c 60\ \ c l i b r e f \ \ " , " m a k e p a t h " , " c " >:
pri ntfC

fP a t h c r e a t e d w i t h _ma k e p a t h : S s \ n \ n " , p a t h_b u f f e r ) ;


_s p l i t p a h ( pa t h_b u f f e r , d r i v e , d i r , f n a m e , ext ) ;
p r i n t f C '" P a t h e x t r a c t e d w i t h _s p l i tp a t h : \ n " ) ;
pri ntfC
pri ntfC
Dri ve : Ss\n " , dri ve > :
Di r : Ss\n" , di r > :
pri ntfC r F i l en ame : S s \ n " , fname > :
pri ntfC r Ext : S s \ n " , ext ) ;

I
I
475 _makepath

Output

P a t h c re a ted w i t h _ma kep a t h : c : \ c 6 0 \ c l i b ref\ma kep a t h . c

P a t h ex t r a c ted w i t h _s pl i t p a t h :
Dri ve : c :
D i r : \ c 60\ c l i b re f \
F i l e n a me : ma kepa t h
Ext : . c
ma/lac unctions 476

Description Allocate m,emory blocks.

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


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

void *malloc( size_t size );


void _based(void) *_bmalloc( _segment seg, size_t size );
void _far *_fmalloc( size_t size );
void _near *_nmalloc( size_t size );

size Bytes to allocate


seg Based heap segment selector

Remadrs Functions in the malloc family allocate a memory block of at least size bytes. The block
may be larger than size bytes because of space required for alignment and maintenance in­
formation. If size is 0, each of these functions allocates a zero-length item in the heap and
returns a valid pointer to that item.
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.
In large data models (compact-, large-, and huge-model programs), malloc maps to
_fmalloc. In small data models (tiny-, small-, and medium-model programs), malloc maps
to · nmalloc.
The _fmalloc function allocates a memory block of at least size bytes in the far heap,
which is outside the default data segment. The return value is a far pointer to void.
The _bmalloc function allocates a memory block of at least size bytes in the based heap
segment specified by the segment selector seg.
The malloc functions allocate memory in the heap segment specified below.

Function Heap Segment

malloc Depends on data model of program


_bmalloc Based heap segment specified by seg value
fmalloc Far heap (outside default data segment)
_nmalloc Near heap (within default data segment)
477 ma/lac Functions

If you are creating programs to run in both real mode and protected mode, you should prob­
ably bind with APILMR.OBJ as well as API.LIB and OS2.LIB. This is necessary if a pro­
gram will use the nmalloc function.
The functions listed below call the malloc family of routines. In addition, the C start-up
code uses malloc to allocate storage for the environ/envp and argv strings and arrays.
The following routines call malloc:

calloc fseek searchenv


execv fsetpos spawnv
execve fullpath spawnve
execvp fwrite spawnvp
execvpe getc spawnvpe
exeel getchar spawn)
execle getcwd spawnle
execlp _getcwd spawnlp
execlpe gets spawnlpe
fgetc getw strdup
fgetchar _popen system
fgets printf scanf
fprint putc setvbuf
fputc putchar tempnam
fputchar putenv ungetc
fputs puts vfprintf
fread putw vprintf
fscanf

The following routines call malloc only in the multithread run-time libraries (LLIBCMT,
LLIBCDLL, CDLLOBJS), not in the regular run-time libraries:

asctime localtime _strerrpr


_beginthread mktime tmpfde
ctime sterror tmpnam
gmtime
ma/lac unctions 478

The following routines call _nmalloc:


nrealloc
I
I
_ncalloc
_nstrdup
realloc (in small data models)

The following routines call _fmalloc:


frealloc
_fcalloc
_fstrdup
realloc (in large data models)

C5. 1 DiNerences In Microsoft C version 5. 1, the _fmallac function would retry allocating within the
default data segment (i.e., in the near heap) if sufficient memory was not available outside the default
data segment. Version 6. O returns NULL under these conditions.

In version 5. 1, the start-up code used ma/lac only if wild-card expansion was used.

The _freec( _memavl, and _memmax functions called ma/lac in version 5. 1 but do not do so in ver­
sion 6.0.

returns a ( void near * ) and fmalloc returns a ( void far * ) The bmalloc function
Return Value The malloc function returns a void pointer to the allocated space. The _nmalloc function

returns a ( void =based( void )* ).


.
- -

The malloc, fmalloc and nmalloc functions return NULL if there is insufficient mem­
-

ory av ailable. The bmalloc function returns _NULLOFF if there is insufficient memory
_

available.
Always check the return from the malloc function, even if the amount of memory re­
quested is small.

Campatlblllty malloc

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

_
bmalloc, _fmalloc, nmalloc
_

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

See A/sa calloc functions, free functions, realloc functions


479 ma/lac Functions

I * MAL LOC . C : T h 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 en frees


* the memo ry w i t h free .
*I

#i n c l ude < s td l i b . h > I * D e f i n i t i on o f _MAX_PATH * /


#i n c l ude < 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 ( )
'{
char *stri ng :

I * A l l o c a t e s p a c e f o r a p a t h n a me * /
s t r i ng = ma l l oc C _MAX_PATH ) ;
i f ( s t r i n g == N U L L )
p r i n t f C " I n s uf f i c i ent memo ry a v a i l a b l e \ n " ) ;
el se
p r i n t f C " M emory s p a c e a l l o c a ted f o r p a t h n a me \ n " ) ;
free ( s t r i ng ) ;
p r i ntf ( " Memory f r e ed \ n " l :

Output

Memo ry s p a c e a l l o c a t e d for p a t h n ame


Memo ry freed
matherr, matherrl 480

Descr/pl/an Handle math errors.

#include <math.h>

int matherr( struct exception * except );


int _matherrl( struct _exceptionl * except );

except Pointer to structure containing error information

Remarks The matherr functions process errors generated by the functions of the math library. The
math functions call the appropriate matherr routine whenever an error is detected. The
_matherrl function 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.
The user can provide a different definition of the matherr or _matherrl function to carry
out special error handling.
When an error occurs in a math routine, matherr is called with a pointer to an exception
type structure (defined in MATH.H) as an argument.
The exception structure contains the following elements:

Element Description

int type Exception type


char *name Name of function where error occurred
double argl, arg2 First and second (if any) argument to function
double retval Value to be returned by function

The type specifies the type of math error. It is one of the following values, defined in
MATH.H:

Value Meaning

DOMAIN Argument domain error


SING Argument singularity
OVERFLOW Overflow range error
PLOSS Partial loss of significance
TLOSS Total loss of significance
481 matherr, _matherrl

UNDERFLOW Underflow range error

The structure member name is a pointer to a null-terminated string containing the name of
the function that caused the error. The structure members argl and arg2 specify the values
that caused the error. (If only one argument is given, it is stored in argl.)
The default return value for the given error is retval. If you change the return value, re­
member that the return value must specify whether an error actually occurred. If the
matherr function returns 0, an error message is displayed and errno is set to an appro­
priate error value. If matherr returns a nonzero value, no error message is displayed, and
errno remains unchanged.

Return Value The matherr functions should return 0 to indicate an error, and a nonzero value to indicate
successful corrective action.

Compatibility matherr

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

_matherrl

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

See Also acos functions, asin functions, atan functions, bessel functions, cabs, cos functions, exp,
hypot, log functions, pow, sin functions, sqrt, tan functions

I * MATH E RR . C : To u s e ma t h e r r , you must t u rn off t h e Extended D i c t i o n a ry


* f l a g w i t h i n t h e M i c ro s oft P r o g r a mme r ' s W o r k B e n c h e n v i ronment , o r u s e t h e
* / N O E l i n k e r opt i on o u t s i d e t h e e n v i ronmen t . For exampl e :
* C L ma t h e r r . c / l i n k / N O E
*I

#i n c l u d e <ma t h . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
matherr, _matherrl 482

v o i d ma i n ( )
[
/ * Do s e e r a l ma t h o p e ra t i o n s t h a t c a u s e e r ro r s . T h e ma t h e r r
* routi e h a nd l e s DOMA I N e r r o r s , b u t l et s t h e s y s t em h a n d l e
* other e r r o r s n o rma l l y .
*I
pri ntf( l og ( - 2 . 0 ) = %e\ n " , l og ( - 2 . 0 ) > :
·
pri ntf C l og 1 0 c - s . 0 > % e \ n " , l og 1 0 C - 5 . 0
= ):
pri ntf C l og ( 0 . 0 ) = %e\ n • , l og ( 0 . 0 ) > :

I * H a n d l e s v e r a l ma t h e r r o r s c a u s ed by pa s s i n g a n e g a t i v e a rg ument
* t o l og o l og 1 0 C DOMA I N e r r o r s ) . When t h i s h a ppen s , ma t h e r r ret u r n s
* t h e n a t u a l o r b a s e - 1 0 l og a r i t hm of t h e a bs o l ute v a l u e of t h e
* a rgument a n d s u p p re s s e s t h e u s u a l e r r o r mes s a ge .
*I
i n t ma t h e r r s t ruct except i on *exc ept )
(
/ * H a nd e DOMA I N e r r o r s f o r l og o r l og 1 0 . * /
i f ( e x c p t - >type == DOMA I N )
[
i f ( s t rcmp C except - > n ame , " l og • ) == 0 )
(
except - > retv a l = l og ( - C except - > a rg l ) > :
p r i n t f C " Sp e c i a l : u s i n g a b s o l ute v a l ue : %s : DOMA I N e r r o r \ n " ,
except - > n ame > :
return 1 :

�1 st
}
i f ( s t rcmp C except - > n a me , " l og 1 0 " > == 0 >

except - > re t v a l = l og 1 0 C - C ex c e pt - > a r g l ) > :


p r i ntf C " Sp e c i a l : u s i n g a bs o l ute v a l ue : % s : DOMA I N e r r o r \ n " ,
except - > n a me > :
return 1 :

el se
[
p r i t f C " N o rma l : • ) ;
ret r n 0 ; / * E l s e u s e t h e defa u l t a c t i o n s * /
483 matherr, _matherrl

Output

S p e c i a l : u s i n g a b s o l u t e v a l u e : l og : DOMA I N e r r o r
l og ( - 2 . 0 > = 6 . 9 3 1 47 2 e - 00 1
Spec i a l : u s i n g a bs o l u t e v a l u e : l og 1 0 : DOMA I N e r r o r
l og 1 0 ( - 5 . 0 > = 6 . 989700e-001
N o rma l : l og : S I N G e r r o r
l og ( 0 . 0 > = - 1 . 7 9 7 6 93e+308
max 484

Description Returns the larger of two values.

#include <Stdlib.h>

type max( type a, type b );

type Any numeric data type


a, b Values of any numeric type to be compared

Rsmarks
I The max macro compares two values and returns the value of the larger one. The argu­
ments can be of any numeric data type, signed or unsigned. Both arguments and the return
I value must be of the same data type.

Rslam Vahle I The macro returns the larger of the two arguments.

Compatibl/lty \ D ANSI • DOS • OS/2 D UNIX D XENIX

BBB Also I min

Exampm �--1-����-

/ * M I NMAX . C * / j I
#i n c l ude < s d l i b . h >
#i n c l ude < s d i o . h >

�oi d ma i n ( )

�0I ;
11 :
i nt a =
i nt b =

p r i n t f C j T h e l a rg e r of %d a n d %d i s % d \ n " , a , b , ma x ( a , b :
p r i n t f ( 1 T h e sma l l e r of %d a n d %d i s % d \ n " , a , b , mi n ( a , b
)
) ;

Output
I 10 21 i s 21
10 21 i s 1 0
T h e l a rg e r j f and
T h e s ma l l e r l of a nd

I
I
I
485 _memavl

Description Returns the size of memory available.

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

size_t _memavl( void );

Remarks The _memavl function returns the approximate size, in bytes, of the memory available for
dynamic memory allocation in the near heap (default data segment). The _memavl func­
tion can be used with calloc, malloc, or realloc in tiny, small, and medium memory mod­
els and with _ncalloc, _nmalloc or _nrealloc in any memory model.
The number returned by the _memavl function may not be the number of contiguous
bytes. Consequently, a call to malloc requesting allocation of the size returned by
_memavl may not succeed. Use the _memmax function to find the size of the largest
available contiguous block of memory.

Return Value The _memavl function returns the size in bytes as an unsigned integer.

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

See Also calloc functions, _freect, malloc functions, _memmax, realloc functions

I * M EMAV L . C : T h i s prog r a m u s e s _mema v l to d e t e rmi n e t h e a m o u n t o f


* memo ry a v a i l a b l e f o r dynami c a l l oc a t i on . I t t h e n u s e s ma l l o c t o
* a l l oc a t e s p a c e for 5 , 000 l on g i n t e g e r s a n d u s e s _mema v l a g a i n t o
* d e t e rmi n e t h e n ew a m o u n t of a v a i l a b l e memory .
*I

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

v o i d ma i n ( )
(
l ong *l ongpt r ;

p r i n t f ( " M em o ry a v a i l a b l e before _nma l l o c = % u \ n " , _mema v l ( l l ;


i f ( C l ongptr _nma l l oc ( 5000 * s i zeof ( l on g l ) ) ! = N U L L l
(
=

p r i n t f ( " Memory a v a i l a b l e a ft e r _nma l l oc = % u \ n " , _mema v l ( ) l ;


_n f r e e ( l on g p t r ) ;
I
_memavt 486

Output I
Memo ry a v a i � a bl e before _nma l l oc - 60906
Memo ry a v a i ll a b l e a ft e r _nma l l oc = 40390
487 memccpy, _fmemccpy

DBSt:rlptlan Copy characters from a buffer.

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


#include <String.h> Use either STRING.ff or MEMORY.ff

void *memccpy( void *dest, void *src, int c, unsigned int count );
void _far * _far _fmemccpy( void _far *dest, void _far *src, int c, unsigned int count );

dest Pointer to destination


src Pointer to source
c Last character to copy
count Number of characters

Remalks The memccpy and _fmemccpy functions copy 0 or more bytes of src to dest, halting when
the character c has been copied or when count bytes have been copied, whichever comes
first.
The _fmemccpy function is a model-independent (large-model) form of the memccpy
function. It can be called from any point in any program.

Return Value If the character c is copied, memccpy or _fmemccpy returns a pointer (or far pointer) to
the byte in dest that immediately follows the character. If c is not copied, memccpy re­
turns NULL.

Campatlblllty memccpy

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

_fmemccpy

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

See Also memchr, memcmp, memcpy, memset

Exampm ��
����--

t * MEMCCPY . C * /
#i n c l u d e <memo ry . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < s t r i n g . h >
memccp , _fmemccpy 488

( 6 0 ] = " T h e q u i c k b rown dog j umps o v e r t h e l a zy fox • :

v o i d ma i n ( >
I

pri ntfC " Fu n c t i on : \ tmemcc py 60 c h a r a c t e r s o r to c h a r a c t e r ' s ' \ n " > :


pri ntf ( • so u r c e : \ t \ t% s \ n " , s t r i n g l > :
pdest = emc cpy ( buffe r , s t r i n g l , ' s ' , 60 > :
*pd e s t = ' \0 ' :
pri ntf C " Re s u l t : \ t \ t % s \ n " , buffe r > :
pri ntf ( " Le n g t h : \ t \ t%d c h a r a c t e r s \ n \ n " , s t r l e n ( buffer ) ) ;

Output

F u n c t i on : memc c py 60 c h a r a c t e r s o r t o c h a r a c t e r ' s '


Source : T h e q u i c k brow n dog j umps o v e r t h e l a zy fox
Res u l t : T h e q u i c k b rown d o g j umps
Lengt h : 25 cha racters
489 memchr, _fmemchr

Description Find characters in a buffer.

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


#include <String.h> Use either STRING.H (for ANSI compatibility) or
MEMORY.H

void *memchr( const void *buf, int c, size_t count );


void _far * _far _fmemchr( const void _far *buf, int c, size_t count );

bu/ Pointer to buffer


c Character to look for
count Number of characters

Remarks The memchr and -fmemchr functions look for the first occurrence of c in the first count
bytes of buf. They stop when they find c or when they have checked the first count bytes.
The _fmemchr function is a model-independent (large-model) form of the memchr func­
tion. It can be called from any point in any program.

Return Value If successful, me�chr or _fmemchr returns a pointer (or a far pointer) to the first location
of c in buf. Otherwise, they return NULL.

Compallblllly memchr

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

fmemchr

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

See Also memccpy, memcmp, memcpy, memset, strchr

Exampm ����
I * M EM CH R . C * /
#i n c l u d e <memo ry . h >
#i n c l u d e < s t d i o . h >
msmchr _tmsmchr j I
490

i nt ch = ' r ' :
char str [ J " l a zy " ;
char stri ng [ ] = " T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox " ;
cha r fmt l [ ] = • 1 2 3 4 5" ;
char fmt2 [ ] = " 1 2345678901 2 3 4 5 67890 1 2 3 4 5 6 7 890123456 78901 234567 890 " ;

v o i d ma i n ( )
I
c h a r *pd s t ;

!
i nt resu t ;

t
p r i n t f ( " St r i ng t o be s e a r c h ed : \ n \ t \ t % s \ n " , s t r i n g l ;
p r i n t f ( " \ t \t%s \ n \ t \ t % s \ n \ n " , fmt l , fmt2 l ;


pri ntf( Sea r c h c ha r : \ t %c \ n " , c h ) ;
pdest = emc h r C s t r i n g , c h , s i zeof ( s t r i n g l l ;
resul t = pdest - stri n g + 1 ;
i f ( pdes != NULL )
pri nt C " Re s u l t : \ t \ t%c found a t pos i t i on %d \ n \ n " , c h , r e s u l t l :
el se
pri nt C " Re s u l t : \ t \ t%c n o t found \ n " l ;

Output

Stri ng to b s e a r c h ed :
T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox
1 2 3 4 5
1 2 34567890 1 2 3 4 5 6 7 89 0 1 2 34 5 6 7 8 9 0 1 2345678901 234567890

Sea r c h c h a r : r
Re s u l t : r found a t p os i t i on 1 2
491 memcmp, _fmemcmp

Description Compare characters in two buffers.

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


#include <string.h> Use either STRING.H (for ANSI compatibility) or
MEMORY.H

int memcmp( const void *buf1 , const void *buj2, size_t count ) ;
int _far _fmemcmp( const void _far *bufl , const void _far *buj2, size_t count );

bufl First buffer


buj2 Second buffer
count Number of characters

Remarks The memcmp and _fmemcmp functions compare the first count bytes of bufl and buj2
and return a value indicating their relationship, as follows:

Value Meaning

<0 bufl less than buj2


=O buf1 identic al to buj2
>0 buf1 greater than buj2

The _fmemcmp function is a model-independent (large-model) form of the memcmp


function. It can be called from any point in program.
There is a semantic difference between the function version of memcmp and its intrinsic
version. The function version supports huge pointers in compact-, large-, and huge-model
programs, but the intrinsic version does not.
.

Return Value The memcmp function returns an integer value, as described above.

Compatibility memcmp

• ANS I • DOS • OS/2 • UNIX • XENIX

_fmemcmp

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


memcmp _lmemcmp r I
I

492

See Also memccpy, memchr, memcpy, memset, strcmp, strncmp


I

I * M EMCMP . C : T h i s p r o g r a m u s e s memcmp to compa r e t h e s t r i n g s na med

r
* f i r s t a n d s e c ond . I f the f i r s t 1 9 byt e s of the s t r i n g s a r e

r
* e q u a l , t h p ro g r a m c on s i d e r s t h e s t r i n g s to be e q u a l .
*/
I
#i n c l ude < s t i n g . h >
#i n c l ude < s t i o . h >

v o i d ma i n ( > ,
I

I

c h a r f i r s [ ] = " 1 2 3 4 5 6 7 890 1 2 34567890 " ;


c h a r s e c o d [ J = " 1 23456 7890 1 2 3456789 1 " ;
i nt resul ;

p r i ntf ( · omp a r e ' % . 1 9 s ' t o ' % . 1 9 s ' :� n · , f i r s t , s e c o n d ) ;


r e s u l t = emcmp ( f i r s t , s e c o n d , 1 9 ) ;
i f ( resul < 0 )
p r i n t f � " F i r s t i s l e s s t h a n s ec o nd . \ n " ) ;

f
e l s e i f ( r e s u l t =� 0 )
p r i n t f � " F i r s t i s eq u a l t o s ec o n d . \ n " ) ;
el se i f ( resul t > 0 )
p r i n t f ( " Fi r s t i s g r e a t e r t h a n s ec o n d . \ n " ) ;
pri ntf ( n ompa r e ' % . 20 s ' t o ' % . 20 s ' : \ n " , f i r s t , s e c o n d ) ;
·

r e s u l t = emcmp ( f i r s t , s e c o n d , 20 ) ;
i f ( resul < 0 )
p r i n t f " F i r s t i s l e s s t h a n s e cond . \ n " ) ;
e l s e i f ( r e s u l t == 0 )
p r i n t f � " F i r s t i s e q u a l to s ec o n d . \ n " ) ;
el se i f ( resul t > 0 )
f
p r i n t f " F i r s t i s g r e a t e r t h a n s ec o n d . \ n " ) ;

I
I
I
493 memcmp, _fmemcmp

Output

Compa re ' 1 2 34567890123456789 ' t o ' 1 2 3 4 5 6 7890 1 2 3 4 5 6 789 ' :


F i r s t i s e q u a l to s e cond .
C ompa re ' 1 2 34567890 1 2 3 4 5 6 7 890 ' to ' 1 234567890 1 2 3 4 5 6 7 89 1 ' :
Fi r s t i s l es s t h a n s e c o n d .

'

memcp _fmemcpy 494

Description Copy characters between buffers.

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


'
#include <string.h> Use either STRING.H (for ANSI compatibility) or
MEMORY.H

void *memcpy( void *dest, const void *src, size_t count );


void _far * _far _fmemcpy( void _far *dest, const void _far *src, size_t count );

dest New buffer


src Buffer to copy from
count Number of characters to copy

Remarks The memcpy and _fmemcpy functions copy count bytes of src to dest. If the source and
destination overlap, these functions do not ensure that the original source bytes in the over­
lapping region are copied before being overwritten. Use memmove to handle overlapping
regions.
The _fmemcpy function is a model-independent (large-model) form of the memcpy func­
tion. It can be called from any point in any program.
There is a semantic difference between the function version of memcpy and its intrinsic
version. The function version supports huge pointers in compact-, large-, and huge-model
programs, but the intrinsic version does not.

Return Value I The memcpy and _fmemcpy functions return a pointer to dest.

I
Compatibilitfr memcpy

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

_fmemcpy

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


495 memcpy, _fmemcpy

See Also memccpy, memchr, memcmp, memmove, memset, strcpy, strncpy

/ * M E M C P Y . C . I l l u s t r a t e o v e r l a pp i n g c o py : memmo v e h a n d l es i t
* c o r re c t l y ; memc py d o e s not .
*I
#i n c l u d e <memo ry . h >
#i n c l u d e < s t r i n g . h >
#i n c l ude < s t d i o . h >

cha r stri ngl [60] " T h e q u i c k b rown d o g j umps o v e r t h e l a zy fox " ;


c h a r s t r i ng2 [ 6 0 ] = " T h e q u i c k b rown fox j umps o v e r t h e l a zy d og " ;
/* 1 2 3 4 5
* 1 2 3 4 5 6 7 89 0 1 2 3 4 5 6 78901 234 5 6 7 890 1 234567890 1 2 34 5 6 7 890
*I
v o i d ma i n ( )
(
p r i n t f ( " Fu n c t i o n : \ tmemcpy w i t h out o v e r l a p \ n " ) ;
p r i n t f ( " So u r c e : \ t \ t % s \ n " , s t r i n g ! + 40 ) ;
p r i n t f ( " De s t i n a t i o n : \ t % s \ n " , s t r i n g ! + 1 6 ) ;
memc py ( s t r i n g l + 1 6 , s t r i n g l + 40 , 3 ) ;
p r i n t f ( " Re s u l t : \ t \ t %s \ n " , s t r i n g l ) ;
p r i n t f ( " Le n g t h : \ t \ t%d c h a r a c t e rs \ n \ n " , s t r l e n ( s t r i n g ! ) ) ;

I * Re s t o r e s t r i n g l t o o r i g i n a l c o n t e n t s * /
memc py ( s t r i n g l + 1 6 , s t r i ng2 + 40 , 3 ) ;

p r i n t f ( " Fu n c t i o n : \ tmemmove wi t h o v e r l a p \ n " ) ;


p r i n t f ( " So u r c e : \ t \ t% s \ n " , s t r i ng2 + 4 ) ;
p r i n t f ( " De s t i n a t i on : \ t %s \ n " , s t r i n g 2 + 1 0 ) ;
memmo v e ( s t r i n g 2 + 1 0 , s t r i ng2 + 4 , 40 ) ;
p r i n t f ( " Re s u l t : \ t \ t % s \ n " , s t r i n g 2 ) ;
p r i n t f ( " Le n gt h : \ t \ t%d c h a r a c t e rs \ n \ n " , s t r l en ( s t r i n g 2 ) ) ;

pri ntf( " Fu n c t i on : \ tmemc py w i t h o v e r l a p\ n " ) ;


pri ntf( " So u r c e : \ t \ t % s \ n " , s t r i n g l + 4 ) ;
pri ntf( " De s t i n a t i o n : \ t % s \ n " , s t r i n g l + 1 0 ) ;
memcpy ( s t r i n g l + 1 0 , s t r i n g l + 4 , 40 ) ;
pri ntf( " Re s u l t : \ t \ t % s \ n " , s t r i n g ! ) ;
pri ntf( " Le n gt h : \ t \ t%d c h a r a c t e rs \ n \ n " , s t r l en ( s t r i n g ! ) ) ;
memcp _lmemcpy f 496

1
Output

F u n c t i on : I memc py w i t h o u t o v e r l a p


S o u rc e : fox

I
Des t i n a t i o : dog j umps over the l a zy fox


Re s u l t : The q u i c k b rown fox j umps over the l a zy fox
Length : 43 c h a r a c t e r s

Functi on : memmo v e wi t h o v e r l a p
Sou rce : q u i c k b rown fox j umps o v e r t h e l a zy dog
Desti nati o : b r own fox j umps o v e r t h e l a zy dog
Re s u l t : I T h e q u i c k q u i c k b r own fox j umps o v e r t h e l a zy dog
Length : ! 49 cha racters

Functi on : I memcpy w i t h o v e r l a p
Source : I q u i c k b r own dog j umps o v e r t h e l a zy fox
D e s t i n a t i op : b rown dog j umps over the l a zy fox
Re s u l t : Th e q u i c k q u i c k q u i c k q u i c k q u i c k q u i c k q u i c k q u i c
Leng t h : I 50 c h a ra c t e r s
491 memicmp, _fmemicmp

Dest:rlpllon Compare characters in two buffers (case-insensitive).

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


#include <String.h> Use either SlRING.H or MEMORY.ff

int memicmp( void *bufl , void *bufl, unsigned int count );


int _far _fmemicmp( void _far *bufl, void _far *bufl, unsigned int count );

bufl First buffer


bufl Second buffer
count Number of characters

Remades The memicmp and _fmemicmp functions compare the first count characters of the two
buffers bufl and bufl byte-by-byte. The comparison is made without regard to the case of
letters in the two buffers; that is, uppercase and lowercase letters are considered equiv­
alent. The memicmp and _fmemicmp functions return a value indicating the relationship
of the two buffers, as follows:

Value Meaning

<0 bufl less than buf2


=0 bufl identical to bufl
>0 bufl greater than bi(l.

The _fmemicmp function is a model-independent (large-model) fonn of the memicmp


function. It can be called from any point in any program.

Rstum Value The memicmp and _fmemicmp functions return an integer value, as described above.

Compal/blllly memicmp

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

_fmemicmp

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


memic p, _lmemicmp 498

See Also memccpy, memcbr, memcmp, memcpy, memset, stricmp, strnicmp

I * M EM I CM . C : T h i s p ro g r a m u s e s memi cmp to c ompa re t h e f i r s t


* 29 l et e r s of t h e s t r i n g s n a med f i r s t a n d s econd w i t h out

l
* re g a rd t o the c a s e of the l et t e r s .
*I

#i n c l u d e m emo ry . h >
#i n c l u d e s t d i o . h>
#i n c l u d e s t r i ng . h >

v o i d ma i n (' )
(
i nt re u l t ;
c h a r f i r s t [ ] = " T h o s e W h o W i l l Not Lea rn f r om H i s t o ry " ;
c h a r s c o n d [ ] = " T H O S E WHO W I L L NOT LEARN F ROM t h e i r mi s t a k e s " ;
I* Not that the 29th cha racter i s ri ght here A */

p r i n t f ( " C omp a r e ' % . 2 9 s ' t o ' % . 2 9 s ' \ n " , f i r s t , s e c o n d ) ;


r e s u l t = memi cmp C f i r s t , s ec o n d , 29 ) ;
i f ( re u l t < 0 )
p r i t f C " Fi r s t i s l e s s t h a n s e c o n d . \ n " ) ;
e l s e i C r e s u l t == 0 >

1
p r i t f ( " Fi r s t i s e q u a l t o s e c o n d . \ n " ) ;
el s e i ( r e s u l t > 0 )
p r i t f ( " Fi r s t i s g r e a t e r t h a n s e c ond . \ n " ) ;

I
I
Output

C ompa re ' h o s e W h o W i l l Not Lea rn f rom ' t o ' TH O S E WHO W I L L NOT L EARN F ROM '
F i r s t i s q u a l t o s ec o n d .
499 _memmax

D1Bt:rlptlan Finds the size of the largest contiguous memory block.

#inchide <malloc.h>

size_t _memmax( void );

The _memmax function returns the size (in bytes) of the largest contiguous block of
memory that can be allocated from the near heap (i.e., the default data segment). Calling
_nmalloc with the value returned by the _memmax function will succeed as long as
_memmax returns a nonzero value.

R1tum Value The function returns the block size, if successful. Otherwise, it returns 0, indicating that
nothing more can be allocated from the near heap.

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

S11 AIBO malloc functions, msize functions

I * M EMMAX . C : T h i s p r o g r a m u s e s _memmax a n d _nma l l oc to a l l o c a t e


* t h e l a rg e s t b l o c k o f memory a va i l a b l e i n t h e nea r h ea p .
*I

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


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

v o i d ma i n ( )
(
s i ze_t c o n t i g ;
c h a r *p ;
_mem ax 500

/ * D e t e mi n e c o n t i g u o u s memo ry s i ze * /
con t i g _memma x ( ) ;
p r i n t f ( " La r g e s t b l o c k of a v a i l a b l e memo ry i s %u by t e s l on g \ n " , con t i g ) ;
i f( con i g )
{
p = nma l l oc ( con t i g * s i z e o f ( i n t l l ;
if( == NULL )
p i n t f ( " E r r o r wi t h ma l l o c ( s h o u l d n e v e r o c c u r l \ n " l ;
el se
{
p i n t f ( " M a x i mum a l l oc a t i on s u c c e e d ed \ n " ) ;
f ee ( p ) ;

)
el se
pri n f( " N ea r h e a p i s a l r e a dy f u l l \ n " ) ;

Output

L a r g e s t b l c k of a v a i l a b l e memo ry i s 60844 by tes l o ng


M a x i mum al oca t i o n s u c c e e d e d
501 ' memmove, _lmemmove

Description Move one buffer to another.

#include <String.h>

void *memmove( void *dest, const void *src, size_t count );


void _far * _far _fmemmove( void _far *dest, const void _far *src, size_t count );

dest Destination object


src Source object
count Number of characters to copy

Remarks The memmove and _fmemmove functions copy count characters from the source (src) to
the destination (dest). If some regions of the source area and the destination overlap, the
memmove and _fmemmove functions ensure that the original source bytes in the overlap­
ping region are copied before being overwritten.
The _fmemmove function is a model-independent (large-model) form of the memmove
function. It can be called from any point in any program.

Return Value The memmove and fmemmove functions return the value of dest.

Compatibllity memmove

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

_fmemmove

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

See Also memccpy, memcpy, strccpy, strncpy

/ * M E M C P Y . C . I l l u s t ra t e o v e r l a p p i n g copy : memmove h a nd l e s i t
* c o r rectl y ; memc py d o e s not .
*I
#i n c l u d e <memo ry . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
,
memm ve, _lmemmove 502

c h a r s t r i n � 2 [ 60 J
c h a r s t r i n � 1 [ 60 J " T h e q u i c k b rown d o g j umps o v e r t h e l a zy fox " ;
" T h e q u i c k b r own fox j umps o v e r t h e l a zy d og " ;
/* 1 2 3 4 5
* 1 2 345678901 23456 7890 1 2 34567890 1 2 34 5 6 7890 1 2 34 5 6 7 890
*I
v o i d ma i n (
{
l ;
I • s o u r c e : \ t \ t% s \ n " , s t r i n g l + 40
pri ntf C . " Func t i on : \ tmemcpy w i t h out o v e r l a p \ n "
pri ntf( l :
" De s t i n a t i on : \ t % s \ n " , s t r i n g l + 1 6 l ;
I
pri ntf(
memc py ( s t r i n g l + 1 6 , s t r i n g l + 40 , 3 l ;

I
pri ntf( " Re s u l t : \ t \ t % s \ n " , s t r i n g l l ;
pri ntf ( . " Leng t h : \ t\t%d c h a r a c t e r s \ n \ n " , s t rl en ( s t r i n g l l l ;

/* Re s t � r e
s t r i ngl to ori gi n a l contents */
memcpy ( s t r i n g l + 1 6 , s t r i n g 2 + 40 , 3 l :

p r i n t f ( " Func t i on : \ tmemmov e w i t h o v e r l a p \ n " l ;


p r i n t f ( " So u r c e : \ t \ t % s \ n " , s t r i n g 2 + 4 l ;

1
p r i n t f ( , " D e s t i n a t i on : \ t % s \ n " , s t r i n g 2 + 1 0 l ;
memmo v e s t r i n g 2 + 1 0 , s t r i n g 2 + 4 , 40 l ;
p r i n t f ( 1 " Re s u l t : \ t \ t % s \ n " , s t r i n g 2 l ;
p r i n t f ( l " Le n g t h : \ t \ t%d c h a r a c t e r s \ n \ n " , s t r l en ( s t r i n g 2 l l ;

pri ntf( ! " Func t i on : \ tmemcpy wi t h overl ap\ n " l ;

! " D e s t i n a t i on : \ U s \ n " , s t r i n g l + 1 0 l ;
pri ntf ( " So u r c e : \ t \ t% s \ n " , s t r i n g l + 4 ) ;
pri ntf(
memcpy ( s t r i n g l + 1 0 , s t r i n g l + 4 , 40 l ;
pri ntf( " Re s u l t : \ t \ t% s \ n " , s t r i n g l l ;
pri ntf ( " Leng t h : \ t \ t %d c h a r a c t e r s \ n \ n " , s t r l en ( s t r i n g l l l ;

Output

F u n c t i on : memcpy w i t h o u t o v e r l a p
Source : fox
D e s t i n a t i on' : dog j umps over t h e l a zy fox
Res u l t : T h e q u i c k b rown fox j umps over the l a zy fox
L e n gt h : 43 c h a r a c t e r s

F u n ct i on : memmo ve w i t h o v e r l a p
Source : q u i c k b rown fox j umps o v e r t h e l a zy dog
D e s t i n a t i on : ·
b rown fox j umps o v e r t h e l a zy dog
Res u l t : T h e q u i c k q u i c k b r own fox j umps o v e r t h e l a zy dog
Length : 49 c h a r a c t e r s
503 memmove, _lmemmove

F u n c t i on : memcpy w i t h o v e r l a p
S o u rc e : q u i c k b rown dog j umps o v e r t h e l a zy fox
Dest i nati on : b r own d o g j umps over the l a zy fox
Res u l t : The qui c k q u i c k q u i c k q u i ck qui c k qui c k qui c k qui c
Lengt h : 50 c h a r a c t e r s
msmsst _fmsmsst 504

Dest:rlpllon Set buffers to a specified character.

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

#include <String.h> Use either STRING.H (for ANSI compatibility) or


MEMORY.ff

void *memset( void *dest, int c, size_t count );


void _far • _far _fmemset( void _far *dest, int c, size_t count );

dest Pointer to destination

c Character to set

count Number of characters

Remal'lcs The memset and _fmemset functions set the first count bytes of dest to the character c.

The _fmemset function is a model-independent (large-model) fonn of the memset func­


tion. It can be called from any point in any program.

There is a semantic difference between the function version of memset and its intrinsic
version. The function version supports huge pointers in compact-, large-, and huge-model
programs, but the intrinsic version does not.

Return Value The memset and _fmemset functions return a pointer to dest.

CampaUblllly memset

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

_fmemset

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

See Also memccpy, memchr, memcmp, memcpy, strnset

Exampm ___,____.;.__
. _________________________________________________________


I * M EM S ET . : T h i s p r o g r a m u s e s mems et t o s et t h e f i r s t f o u r by tes
* of buff r t o " * " .
*I
505 memset, _fmemset

#i n c l ude <memo ry . 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 buff e r [ ] = " T h i s i s a t e s t of t h e memset f u n c t i o n " ;

p r i n t f ( " Be f o r e : % s \ n " , buffer ) ;


mems et ( buff e r , ' * ' , 4 ) ;
p r i n t f ( " Afte r : % s \ n " , buffer ) ;

Output

B e f o r e : T h i s i s a test o f t h e mems et f u n ct i o n
Afte r : **** i s a t e s t of t h e mems et f u n ct i on
min 506

Oest:rlpllan \ Returns the smaller of two values.

#include <Stdlib.h>

type min( type a, type b );

type Any numeric data type

a, b Values of any numeric type to be compared

Remarks The min macro compares two values and returns the value of the smaller one. The argu­
ments can be of any numeric data type, signed or unsigned. Both arguments and the return
value must be of the same data type.

Retum Value The macro returns the smaller of the two arguments.

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

See A/sa max

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

1 * M I NMAX . C * /
#i n c l ude < s d l i b . h >
#i n c l ude < s d i o . h>

�oi d >
'

J
ma i n (

i nt a = 0;
i nt b "' 1;

pri ntf( T h e l a rg e r o f %d a nd %d i s %d\ n " , a , b , m a x ( a , b ) > :


pri ntf( T h e sma l l e r o f %d a nd %d i s % d \ n " , a , b , mi n ( a , b > > :

Output

I
T h e l a rg e r f 10 a n d 2 1 i s 2 1
T h e sma l l e r o f 1 0 a nd 2 1 i s 1 0

I
I
507 mkdir

Description Creates a new directory.

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

int mkdir( char *dirname );

dirname Path name for new directory

Remarks The mkdir function creates a new directory with the specified dirname. Only one
directory can be created at a time, so only the last component of dirname can name a new
directory.
The mkdir function does not do any translation of path-name delimiters. Both DOS and
OS/2 accept either "\" or "/" internally as valid delimiters within path names.

Return Value The mkdir function returns the value 0 if the new directory was created. A return value of
-1 indicates an error, and errno is set to one qf the following values:

Value Meaning

EACCES Directory not created. The given name is the name of an


existing file, directory, or device.
ENOENT Path name not found.

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

See Also chdir, rmdir

Exampre ��
��

I * MAKED I R . C */
#i n c l u d e < d i rect . 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 >
508

(
f

i n t res l t :

i f ( m kd " r ( " \ \ t e s t tmp • > 0 >


(


p r i n f ( " D i rect o ry ' \ \ t e s t tmp ' wa s s u c c e s s f u l l y c re a t e d \ n " > :
s y s t m C " d i r \ \ t e s t tmp " > :
i f ( md i r C " \ \ t e s t tmp • } 0 }
p i n t f ( " D i r e c t o ry ' \ \ t e s t tmp ' wa s s uc c e s s fu l l y remo ved \ n " > :
el se
p i n t f C " P robl em remo v i n g d i rect o ry ' \ \ t e s ttmp ' \ n " > :

el se
p r i n f C " P ro b l em c rea t i n g d i r e c t o ry ' \ \ t esttmp ' \ n " > :

Output

D i rect o ry \ t e s t tmp ' wa s s u c c e s s f u l l y c re a t ed

T h e v o l um l a bel i n d r i v e C i s O S 2 .
D i rect o ry of C : \ T E STTM P

< D I R> 6 - 1 9 - 89 1 1 : 20a


< D I R> 6 - 1 9 - 89 1 1 : 20a
2 Fi l C s > 1 2 7 30368 by t e s f r e e
D i rect o ry \ t e s t tmp ' wa s s u c c e s s f u l l y removed
509 mktemp

D•crlpllan Creates a unique file name.

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

char *mktemp( char *template );

template File-name pattern

Remalks The mktemp function creates a unique file name by modifying the given template argu­
ment. The template argument has the form:

baseXX.XX.XX.
where base is the part of the new file name that you supply, and the X's are placeholders
for the part supplied by mktemp; mktemp preserves base and replaces the six trailing X's
with an alphanumeric character followed by a five-digit value. The five-digit value is a
unique number identifying the calling process. The alphanumeric character is 0 ('0') the
first time mktemp is called with a given template.

In subsequent calls from the same process with copies of the same template, mktemp
checks to see if previously returned names have been used to create files. If no file exists
for a given name, mktemp returns that name. If files exist for all previously returned
names, mktemp creates a new name by replacing the alphanumeric character in the name
with the next available lowercase letter. For example, if the first name returned is
t0 1 2 34 5 and this name is used to create a file, the next name returned will be
ta 1 2 3 4 5 . When creating new names, mktemp uses, in order, 'O' and then the lowercase
letters 'a' through ' z ' .

Note that the original template is modified by the first call to mktemp. If you then call the
mktemp function again with the same template (i.e., the original one), you will get an
error.

The mktemp function generates unique file names but does not create or open files.

Return Value The mktemp function returns a pointer to the modified template. The return value is
NULL if the template argument is badly formed or no more unique names can be created
from the given template.

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


I
mktem � 510

See Also fopen, getpid, open, tempnam, tmpfile

/ * M KT EM P . T h e p ro g r a m u s e s mktemp to c re a t e fi ve un i q u e f i l e n a m e s .
* I t open e a c h f i l e n a m e to e n s u r e t h a t t h e n ext n a me i s u n i q u e .
*/


//i n c l u d e < o . h >
#i n c l u d e < t r i n g . h >

J
#i n c l u d e < td i o . h >


c h a r * t emp l a t e = " fn X X X X X X " ;
cha r *resu t ;

J\
c h a r names 5 J [ 9 J ;

�oi d ma i n O

i nt i :
F I LE *f : 9
for< i lil ; i < 5 ; i ++ )
[
s t rc y ( n ame s [ i J , t empl a t e >:

I * A t empt t o fi nd a u n i q u e fi l e n a me : * /
r e s u l t = mkt emp ( n a m es [ i J > :

l
i f ( e s u l t == N U L L )


p r i n t f ( " P r obl em c r e a t i n g t h e t empl a t e " ) ;
el se
( I
i f c l C fp = fopen ( r e s u l t , " w " ) ) ! = N U L L
p r i n t f ( " U n i q u e f i l e n a me i s % s \ n " , r e s u l t ) ;
el e
p r i n t f ( " C a n n ot open % s \ n " , r e s u l t > :
fc o s e ( fp > :
II

Output

Uni que fi l e name is fnlillillil686


Uni que fi l e n a me is f n a lillil686
U n i q ue fi l e name is fn blillil686
Uni que fi l e name is fn clillil686
Uni que fi l e name is fn dlillil686
511 midime

DBBt:llpllon Converts the local time to a calendar value.

#include <time.h>

time_t mktime( struct tm *timeptr );

timeptr Pointer to time structure

R1matltB The mktime function converts the supplied time structure (possibly incomplete) pointed to
by timeptr into a fully defined structure with "normalized" values and then converts it to a
time_t calendar time value. The structure for the tm is described in the reference page for
asctime.
The converted time has the same encoding as the values returned by the time function.
The original values of the tm_wday and tm_yday components of the timeptr structure are
ignored. and the original values of the other components are not restricted to their normal
ranges.

If successful, mktime sets the values of tm_wday and tm_yday appropriately, and sets
the other components to represent the specified calendar time, but with their values forced
to the normal ranges; the final value of tm_mday is not set until tm_mon and tm_year are
determined.

DOS and OS/2 do not accommodate dates prior to 1 980. If timeptr references a date before
January l , 1980, mktime returns -1 .

Note that the gmtime and localtime functions use a single statically allocated buffer for
the conversion. If you supply this buffer to mktime, the previous contents will be
destroyed.

Retum Value The mktime function returns the specified calendar time encoded as a value of type
time_t If the calendar time cannot be represented, the function returns the value -1 cast as
type time_t.

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

S11 Also asctime, gmtime, localtime, time

I * M KT I M E . C : T h e examp l e t a kes a n umber of d a y s a s i n put a n d ret u r n s


* t h e t i me , t h e c u r re n t d a t e , a nd t h e spec i fi ed n umbe r of d a y s .
*I
1
mktime 512

#i n c l ude < t m e . h >


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

v o i d ma i n ( )
(
s t ruct t w h e n :
t i me_t n w , res u l t ;
i nt d ys ;

t i me ( &n w > :
w h e n = * l oc a l t i me ( & n ow > :
p r i n t f ( C u r rent t i me i s % s \ n " , a s c t i me ( &w hen > >:

j
p r i n t f ( How ma ny d a y s to l oo k a h e a d : • > :
s c a n f ( • d " , &days > :

w h e n . tm_ d a y = w h e n . tm_md ay + d a y s ;
i f ( ( re s l t = m k t i me ( &when ) ) ! = C t i me_t ) - 1 )
p r i n t ( " I n %d d a y s t h e t i me w i l l be % s \ n " ,
d a y s , a s c t i me ( &w h e n > > ;
el se
p e r r o ( " mkt i me fa i l ed " > :

Output

C u r rent t i m i s Mon J u n 1 9 1 1 : 4 5 : 20 1 989

How ma ny d a � s t o l oo k a h e a d : 23
I n 2 3 d a y s l h e t i me w i l l be W e d J u l 1 2 1 1 : 4 5 : 20 1 989
_

I
513 modi, modi/

Dest:rlpllan Split a floating-point value into a mantissa and an exponent.

#include <math.h>

double modf( double x, double *intptr );


long double modtl( long double x, long double *intptr );

x Floating-point value
intptr Pointer to stored integer portion

Remades The modf functions break down the floating-point value x into fractional and integer parts,
each of which has the same sign as x. The signed fractional portion of x is returned. The in­
teger portion is stored as a floating-point value at intptr.

The modtl function uses 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.

Retum Value The modf and modtl functions return the signed fractional portion of x. There is no error
return.

Campatlblllty modf

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

modtl

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

See Also frexp, ldexp

Exampm ����
I * MOD F . C * /
#i n c l ude <ma t h . h >
#i n c l ude < s t d i o . h >
modi, m di/ 514

v o i d ma i n ( )
(
doubl e x i y , n ;

x = J1
- 14 . 7 65432 1 ; / * D i v i d e x i n to i t s f r a c t i o n a l * /

l
y = modf x , &n ) ; / * a nd i n teger pa rts */

1 pri ntfC F o r %f , the f r a c t i on i s %f and the i n teger i s % . f \ n " , x , y , n ) ;

Output

F o r - 14 . 87 6 4 3 , t h e f r a c t i on i s - 0 . 87 6 54 3 a nd t h e i n t e g e r i s - 14
515 movedata

Description Moves characters to another segment.

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


#include <String.h> Use either STRING.ff (for ANSI compatibility) or
MEMORY.ff

void movedata( unsigned int srcseg, unsigned int srcoff, unsigned int destseg,
unsigned int destoff, unsigned int count );

srcseg Segment address of source


srcoff Segment offset of source
destseg Segment address of destination
destoff Segment offset of destination
count Number of bytes

Remarks The movedata function copies count bytes from the source address specified by
srcseg:srcoff to the destination address specified by destseg:destoff.
The movedata function was intended to move far data in small-data-model programs. The
newer model-independent _fmemcpy and _fmemmove functions should be used instead
of the movedata function. In large-data-model programs, the memcpy and memmove
functions can also be used.
Segment values for the srcseg and destseg arguments can be obtained by using either the
segread function or the FP_SEG macro.
The movedata function does not handle all cases of overlapping moves correctly. These
occur when part of the destination is the same memory area as part of the source. The
memmove function correctly handles overlapping moves.

Return Value None.

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


movedat I
516

See Also 1 FP_OFF, FP_SEG, memcpy, memmove, segread

' ������������������������������-
Exampm �--
I * M O V E DATA C *I
#i n c l ude <m mo ry . h >
#i n c l u d e < s di o . h>
#i n c l ude < s ri ng . h>
#i n c l u d e < d s . h>
#i n c l ude <m l l oc . h >

'
c h a r _fa r * r e = " T h i s i s a t e s t . " ;

�oi d ma i n ( )

c h a r _fa � *dest ;
I
i f ( ( d e s i = _fma l l oc ( 80 ) ) ! = N U L L )
{
moved t a ( F P_S E G ( s rc ) , F P_O F F ( s rc ) ,
FP_S E G ( d e s t ) , FP_O F F ( d e s t ) , _f s t r l en ( s rc ) + 1 ) ;
pri nt " T h e s o u rc e d a t a a t % Fp i s ' % Fs ' \ n " , s rc , s rc > :
pri nt " T h e d e s t i n a t i on d a t a a t % Fp i s ' % Fs ' \ n " , d e s t , d e s t ) ;
_ff r e dest ) ;

I
�I[
Output

T h e s o u r c e a t a a t 2 00A : 02 B8 i s ' T h i s i s a t e s t . '


T h e d e s t i n a i on d a t a a t 3008 : 00 1 6 i s ' T h i s i s a tes t . '

I
-I
I
I
517 _maveta Functions

Description Move current graphics positions.

#include <graph.h>

struct xycoord _far _moveto( short x, short y );


struct _wxycoord _far _moveto_w( double wx, double wy ) ;

x, y View-coordinate point
wx, wy Window-coordinate point

Remarks The _moveto functions move the current position to the specified point. The _moveto
function uses the view-coordinate point (x, y) as the current position. The _moveto_w func­
tion uses the window-coordinate point (wx, wy) as the current position. No d�wing takes
place.

Return Value The function returns the coordinates of the previous position. The _moveto function re­
turns the coordinates in an xycoord structure. The xycoord structure, defined in
GRAPH.ff, contains the following elements:

Element Description

short xcoord x coordinate

short ycoord y coordinate

The _moveto_w function returns the coordinates in an _wxycoord structure, defined in


GRAPH.ff. The _wxycoord structure contains the following elements:

Element Description

double wx x window coordinate


double wy y window coordinate

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


_moveto \Functions I

518

SBB A/sa _lineto functions

I * MOV ETO . C :1 T h i s p r o g r a m d ra w s l i n e s egmen t s of d i fferent col o r s . * /

l

/ti n c l u d e < g a p h . h >

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


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

�oi d
I
ma i n { )

s h o rt x , � . x i nc , y i nc , col o r = 1 ;

s t r u c t v i eocon f i g v ;

l
\
I * Fi n d a v a l i d g r a p h i c s mode . * /
i f { ! _s e t v i d eomod e { _MA X C O L O RM O D E

_g et v i d e o f o n f i g ( & v ) ;
exi t ( 1 ) ;

xi nc = v . r umx pi x e l s I 50 ;
yi nc = v . r umypi x e l s I 50 ;


f o r ( x = � . y = v . n umyp i xel s
I
- 1 ; x < v . n umxp i xel s ; x += xi n c , y -= y i n c
I
_s e t c o o r ( col o r++ % 1 6 >:
_mo v e t ( x , 0 ) ;
_l i n e t ( 0 , y ) ;
I
getc h ( ) ;

r
_s et v i d e o od e ( _D E FAU LTMODE ) ;
519 _msize Functions

DllSCllptian Return the size of a memory block allocated in the heap.

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

size_t _msize( void *memblock );


size_t _bmsize( _segment seg, void _based( void ) *memblock ) ;
size_t _fmsize( void _far *memblock );
size_t _nmsize( void _near * memblock );

memblock Pointer to memory block


seg Based-heap segment selector

Remarks The _msize family of functions returns the size, in bytes, of the memory block allocated
by a call to the appropriate version of the calloc, malloc, or realloc functions.
In large data models (compact-, large-, and huge-model programs), _msize maps to
_fmsize. In small data models (tiny-, small-, and medium-model programs), _msize maps
to nmsize.
The _nmsize function returns the size (in bytes) of the memory block allocated by a call to
_nmalloc, and the _fmsize function returns the size (in bytes) of the memory block allo­
cated by a call to fmalloc or frealloc. The bmsize function returns the size of a block
allocated in segment seg by a call to _bmall0c, _bcalloc, or _brealloc.
The location of the memory block is indicated below:
0

Function Data Segment

_msize Depends on data model of program


_bmsize Based heap segment specified by seg v alue
_fmsize Far heap segment (outside default data segment)
_nmsize Default data segment (inside near heap)

Retum Value All four functions return the size (in bytes) as an unsigned integer.

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


I
_msize ,uni:tlons 520

SN Also calloc functions, _expand functions, malloc functions, realloc functions

ExamP• ---1----
I * R EA L LO C . T h i s p r o g r a m a l l o c a t e s a bl o c k o f memo ry f o r buffer
* a nd t h en uses _ms i z e t o d i s p l ay the s i z e of that bl o c k . Next , i t
* u s e s rea l oc to e x p a n d t h e amount of memo ry u s e d by buffer
* a nd t h en c a l l s _ms i z e a g a i n t o d i s p l a y the new amount of
* memo ry a l oc a t e d to b u ffe r .
*I .

#i n c l u d e < s d i o . h >
#i n c l ude <m l l oc . h>
#i n c l ude < s d l i b . h >

v o i d ma i n ( )

[
(
l ong * b u fe r ;
s i z e_t s z e ;

i f ( C b u f e r = ( l o n g * ) ma l l oc C 1000 * s i zeof ( l on g ) ) ) == N U L L )


exi t ( 1 ) ;

s i z e = _ s i z e ( buffer ) ;
p r i n t f ( S i z e of b l o c k a ft e r ma l l oc of 1000 l on g s : % u \ n " , s i z e ) ;

/ * Rea l l c a t e a n d s h ow new s i z e : * /

t
i f ( C buf e r = r e a l l oc C buffe r , s i z e + ( 1 000 * s i zeof C l ong ) ) ) ) == N U L L
exi t C 1 l > :
s i z e = -�s i z e ( buffer l ;
p r i n t f ( r s i z e o f b l o c k a ft e r rea l l oc of 1 000 mo re l on g s : % u \ n " , s i ze ) ; •

free ( b u f e r > :

Output

S i z e of b l o k a ft e r ma l l oc of 1 000 l on g s : 4000
S i z e of bl o k a ft e r rea l l oc o f 1000 more l on g s : 8000
521 onexit

Dest:rlpllon Registers a routine to be called at exit time.

#include <Stdlib.h>

one:xit_t one:xit( one:xit_t June );

June Pointer to function to be called at exit

Rematb The one:xit function is passed the address of a function lfune) to be called when the pro­
gram terminates normally. Successive calls to one:xit create a register of functions that is
executed in LIFO (last-in-first-out) order. No more than 32 functions can be registered
with one:xit; one:xit returns the value NULL if the number of functions exceeds 32. The
functions passed to one:xit cannot take p arameters.

The one:xit function is not part of the ANSI definition, but is instead a Microsoft exten­
sion. The ANSI-standard ate:xit function does the same thing as one:xit, and should be used
instead of one:xit when ANSI portability is desired.

All routines passed to onexit should have the _loadds attribute if used in multithread
dynamic-link libraries.

Return Value The one:xit function returns a pointer to the function if successful and returns NULL if
there is no space left to store the function pointer.

Compallblllty 0 ANSI • DOS • OS/2 • UNIX • XENfx

See Also exit

Exampm ______________________________________________________________�

I* ONEX IT . C *I
#i n c l u d e < s t d l i b . h >
#i n c l ude < s t d i o . h >

I * P rototypes * /
v o i d fn l ( v o i d ) , fn2 C v o i d ) , fn3 C v o i d ) , fn4 ( v o i d l ;
anexit 522

v o i d ma i n ( )
(
onex i t ( n l > :
o n ex i t C n 2 > :
o n ex i t C f n 3 > :

r
o n ex i t ( n4 > :
p r i n t f ( T h i s i s e x e c u t ed f i r s t . \ n " ) ;

voi d fnl C )
(
pri ntf ( next . \ n " ) ;

v o i d fn 2 C )
(
pri ntfC executed • ) ;

v o i d fn 3 C )
(
pri ntf ( is • );

v o i d fn4 ( )
(
pri ntf( Thi s • );

Output

T h i s i s exe uted f i r s t .
T h i s i s e x e uted n e x t .
523 open

Description Opens a file.

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

int open( char *filename, int oflag [, int pmodeD );

filename File name


oflag 'fype of operations allowed
pmode Permission mode

Remarks The open function opens the file specified by filename and prepares the file for subsequent
reading or writing, as defined by oflag. The oflag argument is an integer expression
formed from one or more of the manifest constants defined in FCNTL.H (listed below).
When two or more manifest constants are used to form the oflag argument, the constants
are combined with the bitwise-OR operator ( I ). See Section 2.5, "File Handling," for a dis­
cussion of binary and text modes.
The FCNTL.H file defines the following manifest constants:

Constant Meaning

O_APPEND Repositions the file pointer to the end of the file before every
write operation.
O_BINARY Opens file in binary (untranslated) mode.
O_CREAT Creates and opens a new file for writing; this has no effect if
the file specified by filename exists.
O_EXCL Returns an error value if the file specified by filename exists.
Only applies when used with o_CREAT.
O_RDONLY Opens file for reading only; if this flag is given, neither
O_RDWR nor O_WRONLY can be given.
O_RDWR Opens file for both reading and writing; if this flag is given,
neither 0_RDONLY nor 0_WRONLY can be given.
O_TEXT Opens file in text (translated) mode.
open 524

O_TRUNC Opens and truncates an existing file to zero length; the file
must have write permission. The contents of the file are de­
stroyed. If this flag is given, you cannot specify O_RDONLY.
O_WRONLY Opens file for writing only; if this flag is given, neither
0_RDONLY nor O_RDWR can be given.

WARNING Use the O_ TRUNC flag with care, as it destroys the complete contents of an existing file.

Either O_RDONLY, O_RDWR, or O_WRONLY must be given to specify the access mode.
There is no default value for the access mode.
The pmode argument is required only when 0_CREAT is specified. If the file exists,
pmode is ignored. Otherwise, pmode specifies the file's permission settings, which are set
when the new file is closed for the first time. The pmode is an integer expression contain­
ing one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SYS\STAT.H. When both constants are given, they are joined with the bitwise-OR opera­
tor ( I ) . The meaning of the pmode argument is as follows:

Value Meaning

S_IWRITE Writing permitted


S_IREAD Reading permitted
s_IREAD I s_1wRITE Reading and writing permitted

If write permission 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 permission. Thus the modes S_IWRITE and
S_IREAD I S_IWRITE are equivalent.
The open function applies the current file-permission mask to pmode before setting the per­
missions (see umask).
The filename argument used in the open function is affected by the DOS APPEND com­
mand.
Note that under DOS versions 3.0 and later, a problem occurs when SHARE is installed
and a new file is opened with oflag set to O_CREAT I O_RDONLY or o_CREAT I
0 _WRONLY and pmode set to S_IREAD. Under these conditions, the operating system
prematurely closes the file during system calls made within open. This problem does not
occur under OS/2.
To work around the problem, open the file with the pmode argument set to S_IWRITE.
Then close the file and use chmod to change the access mode back to S_IREAD. Another
work-around is to open the file with pmode set to S_IREAD and oflag set to O_CREAT I
O_RDWR.
525 open

Return Value The open function returns a file handle for the opened file. A return value of -1 indicates
an error, and errno is set to one of the following values:

Value Meaning

EACCES Given path name is a directory; or an attempt was made to


open a read-only file for writing; or a sharing violation oc­
curred (the file's sharing mode does not allow the specified
operations).

EEXIST The 0_CREAT and 0_EXCL flags are specified, but the
named file already exists.

EINVAL An invalid oflag or pmode argument was given.

EMFILE No more file handles available (too many open files).

ENOENT File or path name not found.

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

See Also access, chmod, close, creat, dup, dup2, fopen, sopen, umask

/ * O P E N . C : T h i s p ro g r a m u s e s open to open a f i l e n a med O P E N . C f o r i n put


* and a f i l e n a med O P E N . OUT for output . T h e f i l e s a re t h e n c l o s e d .
*I

#i n c l u d e <fcntl . h>
#i n c l u d e < sy s \ ty p e s . h >
#i n c l u d e <sys \ s ta t . h>
#i n c l u d e < i o . h>
#i n c l u d e < s td i o . h >

v o i d ma i n ( )
{
i n t fh l , f h 2 ;
open 526

I
f h l = open ( " O P E N . C " , O_RDO N LY ) ;
i f ( f h l �= - 1 )


p e r r o l'1' ( " open f a i l ed o n i n p u t f i l e " ) ;

I
l se ·


p r i n t f ( " open s u c c eeded on i n put f i l e \ n " l ;
l cl ose fhl l ;

op 1 n < " O P E N . OUT " , O_WRON LY I O_C REAT , S_I READ


I
fh2 = S_I W R I T E l ;
i f ( f h 2 ""= - 1 )
p e r r o � ( " o pen fa i l ed on output f i l e " ) ;
el se
I !
i

1
p r i n t 1i ( " open s u c c eeded on output f i l e \ n "
cl ose fh2 l ;
l ;

Output
I

open s u c c e e � ed on i n p u t f i l e
open s u c c e e � ed on o u t p u t f i l e
527 _outgtext

Oescrlpl/on Prints font-based text in graphics mode.

#include <graph.h>

void _far_outgtext( unsigned char _far *text );

text Text string to output

Remarks The _outgtext function outputs on the screen the null-tenninated string that text points to.
The text is output using the current font at the current graphics position and in the current
color.

No fonnatting is provided, in contrast to the standard console 1/0 library routines such as
printf.
After it outputs the text, _outgtext updates the current graphics position.
The _outgtext function operates only in graphics video modes (e.g., _MRES4COLOR).
Because it is a graphics function, the color of text is set by the _setcolor function, not by
the _settextcolor function.

Return Value None.

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

See Also ....moveto


. functions, _setcolor, _setfont

I * O UTGTXT . C i l l u s t ra t es font output u s i ng f u n c t i o n s :


* _reg i s te r f o n t s _s et font _outgtext
* _un reg i s te rfonts _getfon t i nfo _getgtextextent
* _s etgtex t v e c t o r
*I

#i n c l u d e <coni o . h>
#i n c l ude <stdi o . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e < s t r i n g . h>
#i n c l ude <graph . h>
_outgte 1'I 528

t
1fd ef i n e N F NTS 6

u n s i gned c � a r *fa c e [ N FONTS]

i
{
=

" C o u r i r " , " He l v e t i c a " , " T i mes Roma n " , " Mo d e rn " , " Sc r i pt " , " Roma n "

� n s i gned
);
l
c a r *opt i o n s [ N FONTS ] =

" c o u r i . r " , " h e l v " , " tms rmn " , " mod e r n " , " s c ri pt " , " roma n "
l: I
!
v o i d ma i n C j

u n s i g n � d c ha r l i s t [ 20 J ;
(

c h a r f � n d i r [_MAX_PAT H ] ;
i'
struct vi deoconfi g vc ;
s t r u c t _font i n fo f i ;
s ho r t o n t n um , x , y ;
I
/ * Rea � h e a d e r i n fo f rom a l l . FO N f i l e s i n c u r r e n t o r g i v e n d i r e c t o ry . * /
i f ( _r , g i s t e rfon t s ( " * . FO N " l <= 0 l
{ .
_o � ttext ( " En t e r f u l l p a t h w h e r e . FO N f i l e s a r e l o c a t ed : • l ;
g et s < fon d i r l ;
s t � c a t ( f o n d i r , " \ \ * . FO N " l ;
1 j
f _reg i s t e rf o n t s ( fondi r ) <= 0 l

_o utt ext ( " E r r o r : c a n ' t re g i s t e r fonts " ) ;


exi t ( 1 ) ;

l
I * Set h i g h e s t a v a i l a b l e g r a p h i c s mode a n d get c o n f i g u ra t i on . * /
i f ( ! _s e t v i deomod e ( _MAX R E S MO D E l l
ex i t ( 1 l ;
_g et v i � e o c o n f i g ( & v c l ;

/ * D i s w l a y ea c h font n a me c e n t e red on s c reen . */


fo r ( f � n t n um = 0 ; f o n t n um < N FONTS ; f o n t n um++ l
( i
/ * ! B u i l d op t i ons s t r i n g . * /
) , "'"l;
s t t c a t ( l i s t , " h 30w24 b " l ;
s t r c a t ( s t rc a t ( s t rc py ( l i s t , " t ' " ) , opt i ons [ fontnum]

i
_c i e a r s c reen ( _GC LEARSC R E E N l;
i f { _s etfont ( l i s t l >= 0 l
{ i
I
529 _outgtext

I * U s e l en g t h o f text a n d h e i ght o f font to c e n t e r text . * /


x = C v c . numx p i x e l s I 2 ) - ( _getgtextextent ( f a c e [ fontnum] ) I 2 ) ;
y = C v c . n umy p i x e l s I 2 > + ( _getgtextex t ent ( fa c e [ fontnum] ) I 2 ) :
i f ( _g etfon t i nfo C & f i ) )
(
_outt ext ( " E r r o r : C a n ' t get font i n forma t i o n " > :
b r ea k :

_mo v e t o ( x , y > :
i f ( v c . numc o l o r s > 2 )
_s etc o l o r < fontnum + 2 > :

I * Rot a te a n d d i s p l ay text . * /
_s e t g t ext v e c t o r ( 1 , 0 l :
_ou t g t ext ( f a c e [ fontnum] > :
_s etgtext v e c t o r ( 0 , 1 > :
_outgtext ( fa c e [ fontnum] > :
_s etgtext v e c t o r ( - 1 , 0 > :
_o utgtext C fa c e [ fontnum] > :
_s e t g t ext v e c t o r ( 0 , - 1 > :
_outgtext C f a c e [ fontnum] > :

el se
(
_o u t t ex t ( " E r ro r : C a n ' t s e t font : • l:
_o u t t ex t ( l i s t > :
}
getc h C > :
}
_u n reg i s te r fonts ( ) ;
_s e t v i d e omod e ( �D E FAU LTMODE > :
_autmet I
530

DBBt:riptlan
I Prints text of a specified length in graphics mode.

#include <graph.h>

void _far _outmem( unsigned char _far *text, short length );

text Text string to output


length Length of string to output

R1matks The _outmem function outputs the string that text points to. The length argument specifies
the number of characters to output.
Unlike _outtext, the _outmem function prints all characters literally, including ASCII 10,
13, and 0 as the equivalent graphics characters. No formatting is provided. Text is printed
using the current text color, starting at the current text position.
To output text using special fonts, you must use the _outgtext function.

Return Value None.

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

See Also _outtext, _settextcolor, _settextposition, _settextwindow

Exampm

----����-

1 * OUTM E M . i l l u s t r a tes :
* _o u t em
I
*I .

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

f
#i n c l ud e < r a p h . h >

�oi d ma i n C

t
i n t i l en ;
char t p [ 10J ;

I
531 _outmem

_c l ea r s c reen ( GC L EARSC R E E N l ;
_

for ( i = 0 ; i < 2 5 6 ; i ++ )
{
_s ettextpos i t i on ( ( i % 24 ) + 1 , ( i I 24 ) * 7 ) ;
l en =s p r i ntf ( tmp , " %3d %c " , i , i l ;
_o utmem ( tmp , l en l ;

_s ettextpos i t i on ( 24 , 1 ) ;
532

I
Description Outputs a byte (outp) or a word (outpw) at a port.

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

int outp( unsigned port, int databyte );


unsigned outpw( unsigned port, unsigned dataword );

port Port number


databyte Output value
dataword Output value

Remarks The outp and outpw functions write a byte and a word, respectively, to the specified out­
put port. The port argument can be any unsigned integer in the range 0 - 65,535; 17yte
can be any integer in the range 0 255; and dataword can be any value in the range
-

0 - 65,535.
Both outp and outpw are supported in OS/2. You must use a .DEF file to declare the
IOSEG segment the run-time library uses to perform input/output on the port. In addition,
the intrinsic (/Oi) versions of these functions do not work unless you put the code in a seg­
ment that is marked with the IOPL keyword in the .DEF file.
You cannot do IOPL from a regular code segment, so the run-time library has declared a
separate code segment called _IOSEG. In order to use inp, inpw, outp, or outp in any of
the protected mode run-time libraries (?LIBCP, LLIBCDLL, LLIBCMT, or CDLLOBJS­
based DLL), you must have a .DEF file with this line in it:
SEGMENTS _I O S E G C LA S S ' I O S E G_C O O E ' IOPL

Return Value The functions return the data output. There is no error return.

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

See Also inp, inpw

I* OUTP . C : T h i s p r o g r a m u s e s i n p a n d o u t p to ma k e s o u n d of v a r i a b l e t o n e
* and dur t i on .
*I
533 outp, outpw

#i nc 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 < t i me . h >

voi d Beep ( u n s i gned


v o i d S l e e p < c l o c k_t
d u r a t i o�. uns i gned frequency ) ; / * P rot otypes * /
wa i t ) ;

voi d ma i n ( )
{
Beep (
Beep (
698 , 700 > :
5 2 3 , 500 > :

* a t a p i t c h s p ec i fi ed i n h e rtz by freq uency .


I * S o u n d s t h e s p e a ker f o r a t i me s p ec i f i ed i n mi c ro s e c o n d s by d u ra t i on

*I
v o i d Beep < un s i gned f r e q u ency , uns i gned d u ra t i on

i nt control :
(

I * I f f r e q u ency i s 0 , Beep d o e s n ' t t ry to ma k e a s ound . * I


i f C freq u e n cy )
{

i f ( d u r a t i on < 7 5 )
I * 7 5 i s a bout t h e s h o r t e s t rel i a bl e d u ra t i on o f a s ound . * /

d u ra t i on = 7 5 ;

I * P repa re t i me r by s end i n g 1 0 1 1 1 100 t o p o r t 43 . * I


outp C 0x43 , 0xb6 > :

* w r i t e ( by t e b y byt e ) t o t i me r .
I * D i v i d e i n put f r e q u ency by t i mer t i c k s p e r s econd a n d

*I
freq uency = C u n s i gned ) ( 1 1 9 3 1 8 0 L I f r e q u en cy ) ;

outp C 0x42 , C c h a r ) C frequency > > 8 ) > :


outp C 0x42 , C c h a r ) frequency ) ;

/* Save s pea k e r c o n t r o l byt e . * /


control = i np ( 0x61 > :

outp C 0x6 1 , c o n t r o l I 0 x 3 ) ;
I * T u r n o n t h e spea k e r ( w i t h b i t s 0 a nd 1 ) . * /

S l eep ( C c l oc k_t ) d u r a t i on > :

I * T u r n s pea k e r ba c k on i f n e c es s a ry . * /
i f ( frequency )
outp C 0x 6 1 , c o n t r o l > :
534

r, I
/ * P a u s e s o r a s p ec i f i ed n umbe r of mi c r o s e c o n d s . * /
v o i d S l eep,.( c l o c k_t wa i t )
(
c l o c k_ f goal ;

goa l =11wa i t + c l o c k ( ) ;
w h i l e ( g o a l > c l oc k ( ) )
535 _outtext

Description Prints text in graphics mode.

#include <graph.h>

void _far _outtext( unsigned char _far *text );

text Text string to output

Remarks The _outtext function outputs the null-tenninated string that text points to. No fonnatting
is provided, in contrast to the standard console 1/0 library routines such as printf. This
function will work in any screen mode.

Text output begins at the current text position.


To output text using special fonts, you must use the _outgtext function.

Return Value None.

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

See Also _outmem, _settextcolor, _settextposition, _settextwindow

I * OUTTXT . C : T h i s exampl e i l l u s t r a tes text output func t i on s :


* _g ettext c o l o r _g e t b k c o l o r _g ettextpos i t i on _outtext
* _s ettext c o l o r _s etbkcol o r _s ettextpos i t i on
*/

#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 ude < g r a p h . h >

c h a r b u f f e r [ 80 ] ;

v o i d ma i n ( )
{

/ * S a v e o r i g i n a l foreground , b a c k g round , a nd text pos i t i on * /


s h o rt b l i n k , fgd , o l dfgd ;
l on g bgd , o l dbgd ;
s t ru c t r c c o o rd o l d p o s ;
_outtextl 536

j
/ * S a v e o r i g i n a l foreg round , b a c k g round , a n d text po s i t i on . * /

�1
o l dfgd , _gettextcol o r ( ) ;
o l dbgd =: _g etb k c o l o r ( ) ;
o l dpos _g ettextpos i t i on ( ) ;
_c l ea rs reen ( _GClEARSC R E E N ) ;

/ * F i r s � t i me n o b l i n k , s e c o n d t i me bl i n k i n g . * /
f o r { b l i [ n k = 0 ; bl i n k < = 1 6 ; bl i n k += 1 6 )
{ .
l
I * L op t h ro u g h 8 b a c k g ro u n d c o l o r s . * /

(
fo r < b g d = 0 ; b g d < 8 ; bg d++ )

1
_s � t b k c o l o r < bgd ) ;
_s ettextpos i t i on ( ( s h o rt l bgd + ( ( b l i n k I 1 6 ) * 9 ) + 3 , 1 ) ;


-�ettext c o l o r ( 7 ) ;

1
s r i n t f ( buffe r , " Ba c k : %d Fore : " , bgd ) ;
- uttext ( buffer ) ;

/ � Loop t h r o u g h 1 6 foreground c o l o r s . * /
for ( fgd = 0 ; fgd < 1 6 ; fgd++ )
(
_s ettextc o l o r ( fgd + b l i n k ) ;
s p r i ntf ( buffe r , • %2d • , fgd + b l i n k ) ;
_o uttext ( buffer ) ;

getc h ( ) ;
I,
/ * Re s t o r e o r i g i n a l foreground , b a c k g r o u n d , and text p o s i t i on . */

_s e t b k c o� o r < ol dbgd ) ;
_s ettex t c o l o r ( o l dfgd ) ;

(
_c l ea r s c ! r een { _GC L EARSC R E E N ) ;
_s ettext p o s i t i on ( o l dpos . row , o l dpos . c o l ) ;

I
537 _pclose

Dsscr/plian Waits for a child command and closes the stream on the associated pipe.

#include <Stdio.h> Function declaration

int _pclose( FILE *stream );

stream File stream returned by previous c all to _popen

Remarks The _pclose function waits for a child command and closes the stream on the associated
pipe. The argument stream is the return value from a previous call to _popen. The _pclose
function looks up the process ID of the child command started by the associated _popen
call, closes the stream, executes a cwait call on the child command, and returns the exit sta­
tus of the child command. See _pipe for a general discussion of pipes in OS/2.

Rstum Value The _pclose function returns the exit status of the child command. The format of the return
value is the same as that for cwait, with the exception that the low-order and high-order
bytes are swapped. If an error occurs, -1 is returned.

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

A similar function (pclose) is available in the XENIX and UNIX operating environments.

See A/BO cwait,. _pipe, _popen

Example See the example for _popen.


perror 538

OeBt:tipUan Prints an error message.

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

void perror( const char *string );

string String message to print

Remades The perror function prints an error message to stderr. The string argument is printed first,
followed by a colon, then by the system error message for the last library call that pro­
duced the error, and finally by a newline character. If string is a null pointer or a pointer to
a null string, perror prints only the system error message.
The actual error number is stored in the variable errno (defined in ERRNO.H). The sys­
tem error messages are accessed through the variable sys_errlist, which is an array of mes­
sages ordered by error number. The perror function prints the appropriate error message
by using the ermo value as an index to sys_errlist. The value of the variable sys_nerr is
defined as the maximum number of elements in the sys_errlist array.

To produce accurate results, perror should be called immediately after a library routine re­
turns with an error. Otherwise, the errno value may be overwritten by subsequent c alls.
Under DOS and OS{l, some of the ermo values listed in ERRNO.H are not used. These
additional errno values are reserved for UNIX and XENIX use. See Section 3.3,
"_dosermo, ermo, sys_errlist, sys_nerr," for a list of ermo values used on DOS and
OS{l and the corresponding error messages. The perror function prints an empty string
for any ermo value not used under the operating system.

Return Value None.

CampaUbll/ly • ANSI B DOS • OS/2 • UNIX • XENIX

I
See Also clearerr, ferror, strerror

Examp� --�---------------------------------------------------
1 * P E RROR . c J T h i s p r o g r a m a t t empts t o open a f i l e n a med NOSUCH F . I LE .

l
* S i n c e t h 1 s f i l e p r o ba b l y d o e s n ' t exi s t , a n e r r o r mes s a g e i s d i s p l ayed .
* T h e s a me m e s s a g e i s c re a t ed u s i n g p e r ro r , s t re r ro r , a n d _s t re r ro r .
*I

I
539 perror

#i n c l u d e <fcntl . h>
#i n c l u d e < s y s \ types . h >
#i n c l u d e < s y s \ s t a t . h>
#i n c l u d e < i o . h>
#i ncl ude <stdl i b . h>
#i n c l u d e < s td i o . h >
#i n c l u d e <stri ng . h>

v o i d ma i n < >
[
i n t fh :

i f ( ( fh = open ( " N OSUC H F . I L E " , O_RDON LY ) ) == - 1


[
I * T h ree ways to c r e a t e e r r o r mes s a g e : * I
p e r r o r ( " pe r ro r s a y s o p e n fa i l ed " > :
p r i n t f ( " s t re r r o r s a y s open fa i l ed : % s \ n " , s t re r ro r ( e r rn o ) > :
p r i n t f ( _s t re r ro r ( •_s t re r r o r s a y s op en fa i l ed " ) > :

el se
[
p r i ntf C " open s u c c e e d ed on i n put f i l e \ n " > :
cl ose( fh > :

p e r r o r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
s t re r r o r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
_s t r e r ro r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
I
l
1
I

-P1L... an /yzechatt Functions 540

Description Analyze a series of data.

#include <pgchart.h>

short _far _pg_analyzechart( chartenv _far *env, char _far * _far *categories,
tloat _far *values, short n ) ;

short _far _pg_analyzechartms( chartenv _far *env, char _far * _far *categories,
tloat _far *values, short nseries, short n, short arraydim,
char _far * _far *serieslabels ) ;

env Chart environment variable


categories Array of category variables
values Array of data values
nseries Number of series to chart
n Number of data values to chart
arraydim Row dimension of data array
serieslabels Array of labels for series

Rematks The _pg_analyzechart routines an alyze a single or multiple series of data without actually
displaying the presentation-graphic image.
The _pg_analyzechart function fills the chart environment with default values for a
single-series bar, column, or line chart, depending on the type specified by the call to the
_pg_defaultchart function. The variables calculated by _pg_analyzechart reflect the data
given in the arguments categories and values. All arguments are the same as those used
with the _pg_chart function.
The _pg_analyzechartms function fills the chart environment with default values for a
multiseries bar, column, or line chart, depending on which type is specified in the
_pg_defaultchart function. The variables calculated by _pg_analyzechartms reflect the
data given in the arguments categories and values. All arguments are the same as those
used with the _pg_chartms function.
Boolean flags in the chart environment, such as AUTOSCALE and LEGEND, should be set
to TRUE before calling either _pg_analyzechart function. This will ensure that the func­
tion will calculate all defaults.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
541 _ pg ana/yzechart Functions
_

Return Value The _pg_analyzechart and _pg_analyzechartms functions return 0 if there were no er­
rors. A nonzero value indicates a failure.

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

See Also _pg_chart functions, _pg_defaultchart, _pg_initchart

Exampm ������-
1* P GACHART . C : T h i s e x a mpl e i l l u s t ra t e s p r e s e n t a t i o n - g r a p h i c s
* a n a l yze f u n c t i o n s .
* T h e exampl e u s e s
* _p g_a n a l y z e c h a rtms
* The s ame p r i n c i pl e s a ppl y f o r
* _pg_a n a l yzepi e _pg_a n a l yze c h a rt
*
_pg_a n a l y z e s c a t t e r _pg_a n a l y z e s c a t t e rms
*I

#i n c l u d e <coni o . h>
#i n c l u d e <stri ng . 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 n c l u d e < p g c h a rt . h >

#d e f i n e FA L S E 0
f/d e f i n e T RU E 1

I* Note d a t a d e c l a red as a s i n g l e - d i men s i o n a r ray . The mul t i s e r i e s


* c h a rt f u n c t i o n s e x p e c t o n l y one d i men s i o n . See _pg_c h a rtms
* exampl e for a l t e r n a t e met h od u s i n g mul t i d i mens i on a r ray .
*/
#d ef i n e TEAMS 4
#d ef i n e MONTHS 3
f l o a t _fa r v a l u e s [ T EAMS * MONTH S ] . 4 35 , . 522 , . 67 1 ,
. 5 33 , . 43 1 , . 5 90 ,
. 7 23 , . 6 24 , . 488 ,
. 3 29 , . 226 , . 40 1 };
c h a r _fa r *mon t h s [ MONTH S J = " May • , " J un e " , " J u l y " } ;
c h a r _fa r *teams [ T EAM S J = { " Red s " , " Sox " , " C ub s " , " Me t s • } ;

v o i d ma i n ( }
{
c h a rtenv e n v :

I * Fi nd a v a l i d g r a p h i c s mode . * /
i f ( ! _s e t v i deomod e ( _MAX RESMOOE )
ex i t ( 1 ) :

_pg_i n i t c h a rt ( ) : I * I n i t i a l i z e c h a rt sys tem . */


_pg_ana yzechart Functions 542

I * Defa u t mul t i s e r i e s ba r c h a rt * /
_pg_d efa l t c h a rt ( &en v , _PG�BA RCHART , _P G_P LA I N BARS ) ;
s t rc py ( n v . ma i n t i t l e . t i t l e , " L i tt l e Lea g u e Rec o r d s - Defa u l t " > :
_pg_c h a r ms < &en v , mont h s , v a l u e s , T EAMS , MONTH S , MONTHS , t e a ms > :
getch < > :
_c l ea rs reen C _GC L EA R S C R E E N ) ;

I * Ana l y e mul t i s e r i e s ba r c h a rt w i t h a ut o s c a l e . T h i s s e t s a l l
* d e f a u t s ca l e v a l u e s . We w a n t y a x i s v a l u e s t o be a utoma t i c .
I
_pg_d efa � l t c h a rt C & e n v , _PG_BA RCHART , _PG_P LA I N BARS ) ;

r
*I

s t rcpy ( e n v . ma i n t i t l e . t i t l e , " L i t t l e L e a g u e Rec o r d s - C u s t om i zed " ) ;


env . x a x i . a ut o s c a l e = T RU E i
_pg_a n a l z e c h a rtms C &en v , mont h s , v a l ues , T EAMS , MONTH S , MONTHS , t e a ms ) ;

/ * N ow c s t omi z e s ome o f t h e x a x i s v a l u e s . Then d ra w t h e c h a rt . * /


env . x a x i . a ut o s c a l e = FAL S E :
env . x a x i . s c a l em a x - 1 . 0 ; / * M a k e s ca l e s how 0 . 0 t o 1 . 0 . */
env . xa x i . t i c i n t e rv a l - 0 . 2 : / * Don ' t ma ke s c a l e too c rowded . * /
env . x a x i . t i c d ec i ma l s - 3 : / * S h ow t h ree d ec i ma l s . */
s t rc py ( n v . x a x i s . s c a l eti t l e . t i t l e , " W i n / Lo s s P e r c e n t a g e " > :
_pg_c h a r ms ( &env , mon t h s , v a l u e s , T EAMS , MONTH S , MONTH S , t e a ms > :
getc h ( ) ;

_s et v i d e mod e ( _D E FAU LTMO D E ) ;


_pg_analyzepie

DBICllptlan Analyzes a single series of data for a pie chart.

#include <pgchart.h>

short _far _pg_analyzepie( chartenv _far *env, char _far * _far *categories,
float _far *values, short _far *explode, short n ) ;

env Chart environment variable

categories Array of category variables

values Array of data values

explode Array of explode flags

n Number of data values to chart

Remades The _pg_analyzepie function analyzes a single series of data without actually displaying
the graphic image.

The _pg_analyzepie function fills the chart environment for a pie chart using the data con­
tained in the array values. All arguments are the same as those used in the _pg_chartpie
function.

For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."

RBlum Value The _pg_analyzepie function returns 0 if there were no errors. A nonzero value indicates a
failure.

CampaUblllty D ANSI B DOS D OS/2 D UNIX D XEN IX

S11 A/sa _pg_chartpie, _pg_defaultchart, _pg_initchart

Example See the example for _pg_analyzechart


I
I

_pg_ana yzescatter Functions 544

Dest:rlpllan Analyze a series of data for a scatter chart.

#include <pgchart.h>

short _far _pg_analyzescatter( chartenv _far *env, float _far *xvalues,


float �far *yvalues, short n );
short _far _pg_analyzescatterms( chartenv _far *env, float _far *xvalues,
float _far *yvalues, short nseries, short n, short rowdim,
char _far * _far *serieslabels );

env Chart environment structure


xvalues Array of x-axis data values
yvalues Array of y-axis data values
n Number of data values to chart
nseries Number of series to chart
rowdim Row dimension of data array
serieslabels Array of labels for series

Remalks The _pg_analyzescatter set of routines analyzes a single or multiple series of data without
actually displaying the graphic image.
The _pg_analyzescatter function fills the chart environment for a single-series scatter dia­
gram. The variables calculated by this function reflect the data given in the arguments
xvalues and yvalues. All arguments are the same as those used in the _pg_chartscatter
function.
The _pg_analyzescatterms function fills the chart environment for a multiseries scatter di­
agram. The variables calculated by _pg_analyzescatterms reflect the data given in the ar­
guments xvalues and yvalues. All arguments are the same as those used in the function
·

_pg_chartscatterms.
Boolean flags in the chart environment, such as AUTOSCALE and LEGEND, should be
set to TRUE before calling _pg_analyzescatterms; this ensures that the function will cal­
culate all defaults.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."

Return Value The _pg_analyzescatter and _pg_analyzescatterms functions return 0 if there were no er­
rors. A nonzero v alue indicates a failure.
545 _pg_analyzescatter Functians

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

See Also _pg_chartscatter functions, _pg_defaultchart, _pg_initchart

Example See the example for _pg_analyzechart.


_pg_cha Functions 546

DlllfJflptlon Display single-series or multiseries charts.

#include <pgchart.h>

short _far _pg_chart( chartenv _far *env, char _far * _far *categories,
float _far *values, short n );

short _far _pg_chartms( chartenv _far *env, char _far * _far *categories,
float _far *values, short nseries, short n, short arraydim,
char _far * _far *serieslabels );

env Chart environment variable

categories Array of category variables

values Array of data values

n Number of data values to chart

nseries Number of series to chart

arraydim Row dimension of data array

serieslabels Array of labels for series

Rematkl The _pg_chart function displays a single-series bar, column, or line chart, depending on
the type specified in the chart environment variable (env).

The _pg_chartms function displays a multiseries bar, column, or line chart, depending on
the type specified in· the chart environment. All the series must contain the same number of
data points, specified by the argument n.

The array values is a two-dimensional array containing all value data for every series to
be plotted on the chart. Each column of values represents a single series. The parameter
rowdim is the integer value used to dimension rows in the array declaration for values.
For example, the following code fragment declares the identifier v a 1 ues to be a two­
dimensional floating-point array with 20 rows and 1 0 columns:

#d ef i n e A RRAY D I M 20
fl o a t v a l u e s [ A R RAY D I M ] [ 1 0 ] ;
s h o r t rowd i m = A R RAY D I M ;

Note that the number of columns in the values array cannot exceed 10, the maximum num­
ber of data series on a single chart. Note also that row d i m must be greater than or equal
to the argument n, and the column dimension in the array declaration must be greater than
or equal to the argument nseries. If n and nseries are set to values less than the full dimen­
sional size of the values array, only part of the data contained in values will be plotted.
547 _pg_chart Functions

The array series/abels holds the labels used in the chart legend to identify each series.

For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."

Retum Value The _pg_chart and _pg_chartms functions return 0 if there were no errors. A nonzero
value indicates a failure.

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

See Also _pg_analyzechart functions, _pg_defaultchart, _pg_initchart

I * PGCHART . C : T h i s examp l e i l l u s t r a t e s p r e s e n t a t i o n - g ra p h i c s s u pport


* r o ut i nes and s i n g l e - s e r i e s c h a rt routi nes , i n c l u d i n g
* _pg_i n i t c h a rt _pg_d e f a u l t c h a rt _pg_c h a rt _pg_c h a rtpi e
*/

#i n c l u d e < c on i o . h >
#i n c l u d e <graph . h>
#i n c l u d e <stri ng . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e < p g c h a rt . h >

#d ef i n e COUNT R I E S 5
fl o a t _fa r v a l u e [ COUNT R I E S ] = 42 . 5 , 14 . 3 , 35 . 2 , 21 . 3 , 32 . 6 };
c h a r _fa r * c a t e g o ry [ CO U NT R I E S J = "USSR" , " F r a n c e " , " U SA " , "UK" , " Ot h e r • J ;
s h o rt _fa r expl od e [ CO U N T R I E S ] = 0, 1, 0, l, 0 };

v o i d ma i n ( )
{
c h a rtenv e n v ; .
s ho r t mode _V R E S 1 6 C O LO R ;
=

I * Fi nd a v a l i d g r a p h i c s mode . * I
i f ( ! _s e t v i d e omod e C _MA X R E SMO D E )
exi t ( 1 ) ;

_pg_i n i t c h a rt ( ) ; / * I n i t i a l i ze c h a rt sys tem . * I

/ * S i n g l e - s e r i e s b a r c h a rt * /
_pg_d efa u l t c h a r t C &en v , _PG_BARCHART , _PG_P LA I N BARS ) ;
s t r c py C e n v . ma i n t i t l e . t i t l e , " W i dget P r o d u c t i on • ) ;
_pg_c h a rt C & e n v , c a t e g o ry , va l u e , COUNT R I E S > :
·

getch ( ) ;
_c l ea r s c reen C _GC LEARS C R E E N ) ;
548

l
I * S i n g e - s e r i e s c o l umn c h a rt * /
_pg_d ef u l t c h a rt ( &env , _PG_COLUMN CHART , _PG_P LA I N BARS ) ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " W i dget P roduct i on • > ;
_pg_c h a t C &env , c a t e g o ry , v a 1 u e , C O U NT R I E S > ;
getc h C > �

I* Pi e
_pg_d ef
s t rcpy (
l
_c l e a r s l reen ( _GC L EARSC R E E N ) ;

h a rt * /
u l t c h a rt ( &env , _PG_P I ECHART , _PG_P E R C E N T ) ;
e n v . ma i n t i t l e . t i t l e , " W i dget P roduct i on • ) ;

1
_pg_c h a t p i e C &en v , c a tegory , v a l u e , expl ode , C O U NT R I E S ) ;
getc h ( ) .
_s et v 1 d omode C _O E FAU LTMOD E > :
549 _ pg chartpie
_

Description Displays a pie chart.

#include <pgchart.h>

short _far _pg_chartpie( chartenv _far *env, char _far * _far *categories,
float _far *values, short _far *explode, short n );

env Chart environment structure


categories Array of category labels
values Array of data values
explode Array of explode flags
n Number of data values to chart

Remarks The _pg_chartpie function displays a pie chart for the data contained in the array values.
Pie charts are formed from a single series of data-there is no multiseries version of pie
charts as there is for other chart types.
The array explode must be dimensioned so that its length is greater than or equal to the
argument n. All entries in explode are either 0 or 1 . If an entry is 1 . the corresponding pie
slice is displayed slightly removed from the rest of the pie.
For example if the explode array is initialized as
.
s h o r t expl ode [ 5 J = { 0 , 1 , 0 , 0 , 0 } ;

the pie slice corresponding to the second entry of the categories array will be displayed
"exploded.. from the other four slices.
For a discussion of the chart environment and related topics, see Section 2.6.2.
"Presentation-Graphics Functions.••

Return Value The _pg_chartpie function returns 0 if there were no errors. A nonzero value indicates a
failure.

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

See Also _pg_analyzepie, _pg_defaultchart. _pg_initchart

Example See the example for _pg_chart.


_pg_cha �
i

atter Functlons 550

D11scrlptlon Display scatter charts.

#include <pgchart.h>

short _far _pg_chartscatter( chartenv _far *env, float _far *xvalues,


float _far *yvalues, short n );
short _far _pg_chartscatterms( chartenv _far *env, float _far *xvalues,
float _far *yvalues, short nseries, short n, short rowdim,
char _far * _far *serieslabels );

env Chart environment structure

xvalues Array of x-axis data values

yvalues Array of y-axis data values

n Number of data values to chart

nseries Number of series to chart

rowdim Row dimension of data array

series/abets Array of labels for series

The _pg_chartscatter function displays a scatter diagram for a single series of data.

The _pg_chartscatterms function displays a scatter diagram for more than one series
of data.

The arguments xvalues and yvalues are two-dimensional arrays containing data for the
x axis and y axis, respectively. Columns for each array hold data for individual series; thus
the first columns of xvalues and yvalues contain plot data for the first series, the second
columns contain plot data for the second series, and so forth.

The n, rowdim, nseries, and serieslabels arguments fulfill the same purposes as those used
in the _pg_chartms function. See _pg_chartms for an explanation of these arguments.

For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."

R11tum Valu11 The _pg_chartscatter and _pg_chartscatterms functions return 0 if there were no errors.
A nonzero value indicates a failure.
551 _pg_chartscatter Functions

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

See Also _pg_analyzescatter functions, _pg_defaultchart, _pg_initchart

Example See the example for _pg_chart.


_pg det ultchart
_ 552

D•crlptlon Initializes the chart environment.

#include <pgchart.h>

short _far _pg_defaultchart( chartenv _far *env, short charttype, short chartstyle );

env Chart environment structure

charttype Chart type

chartstyle Chart style

Remades The _pg_defaultchart function initializes all necessary variables in the chart environment
for the chart type by the variable charttype.

All title fields in the environment structure are blanked. Titles should be set in the proper
fields after calling _pg_defaultchart

The charttype variable can be set to one of the following manifest constants:

Chart Type Descriptie>n


_PG BARCHART
_ Bar chart
_PG COLUMNCHART
_ Column chart
_PG LINECHART
_ Line chart
_PG PIECHART
_ Pie chart
_PG SCATTERCHART
_ Scatter chart

The chartstyle variable specifies the style of the chart with either the number " l " or the
number "2." Each of the five types of presentation-graphics charts can appear in two differ­
ent chart styles, as described below:

Chart Type Chart Style 1 Chart Style 2

Bar Side by side Stacked


Column Side by side Stacked
Line Points with lines Points only
Pie Percent No percent
Scatter Points with lines Points only
553 _pg_ defaultc h art

In a pie chart, the pieces are "exploded" according to the explode array argument in the
_pg_chartpie function. In the "percent" format, percentages are printed next to each slice.
Bar and column charts have only one style when displaying a single series of data. The

on the same chart. The first style arranges the bars or coldmns for the different series side
styles "side by side" and "stacked" are applicable only when more than one series appear

by side, showing relative heights or lengths. The stacked style emphasizes relative sizes be­
tween bars and columns.

Retum Value The _pg_defaultchart function returns 0 if there were no errors. A nonzero value indi­
cates a failure.

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

See Also _pg_getchardef, _pg_getpalette, _pg_getstyleset, _pg_hlabelchart, _pg_initchart,


_pg_resetpalette, _pg_resetstyleset, _pg_setchardef, _pg_setpalette, _pg_setstyleset,
_pg_vlabelchart

Example See the example for _pg_chart.


I
_pf_g,hardef 554

01JSC1/pllan Gets the pixel bit map for the specified character.

#include <pgchart.h>

short _far _pg_getchardef( short chamum, unsigned char _far *chardef );

charnum ASCII number of character

chardef Pointer to 8-by-8 bit map array

Rematks The _pg_getchardef function retrieves the current 8-by-8 pixel bit map for the character
having the ASCII number charnum. The bit map is stored in the chardefarray.

Retum Value The _pg_getchardef function returns 0 if there were no errors. A nonzero value indicates
an error.

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

See Also _pg_defaultchart, _pg_initchart, _pg_setchardef


555 _pg_getpalette

DacrlpUon Gets palette colors, line styles, and patterns.

#include <pgchart.h>

short _far _pg_getpalette( paletteentry _far *palette );

palette Pointer to first palette structure in array

Remarks The _pg_getpalette function retrieves palette colors, line styles, fill patterns, and plot char­
acters for all palettes. The pointer palette points to an array of palette structures that will
contain the desired palette values.
The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.

Return Value The function _pg_getpalette returns 0 if there were no errors, and it returns the value
_BADSCREENMODE if current palettes have not been initialized by a previous call to
_pg_setpalette.

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

See Also _pg_defaultchart, _pg_initchart, _pg_resetpalette, _pg_setpalette

I * PGGPAL . C : T h i s exampl e i l l u s t r a t e s p r e s e n t a t i o n - g ra p h i c s p a l e t t e s
* a n d t h e rout i n e s t h a t mod i fy t h em , i n c l u d i ng
* _pg_g e t p a l ette _pg_res etpa l ette _pg_s et s ty l e s e t
* _pg_g e t s ty l e s e t _pg_res e t s ty l e s et _pg_v l a b e l c h a rt
* _pg_h l a be l c h a rt _pg_s etpa l et t e
*I
#i n c l u d e < c on i o . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d l i b . h >
#i n c l u d e < g r a p h . h >
#i n c l u d e < p g c h a rt . h>
556

{ { . 43 5 , . 522 , . 67 1 } .
{ . 533 , . 431 , . 40 1 } } ;
{ " Ma y " , " J u n e " , " J u l y " } ;
" Reds • } ;

0 x c c , 0x99 , 0x33 , 0 x 6 6 , 0xcc } ;


0x33 , 0x99 , 0x c c , 0x66 , 0x33 } ;

/ * F i n d a v a l i d g r a p h i c s mod e . * I
i f ( ! _s e t i d eomode ( _MA X RE SMOO E )
ex i t ( 1 ) ;

_pg_i n i t c h a rt C ) ; / * I n i t i a l i z e c h a rt s y s t em . */

I * Mod i fy g l oba l s e t o f l i n e s ty l e s u s e d f o r bord e r s , g r i d s , a n d


* d a t a con n e c t o r s . N o t e t h a t t h i s c h a n g e i s u s e d before
* _p g_d efa u l t c h a rt , w h i c h w i l l use the s ty l e s e t .
*I
_pg_g e t s t l e s e t C s ty l e s ) ; I * Get s ty l e s a n d mod i fy */
s tyl e s [ l ] = 0 x 5 5 5 5 ; /* styl e 1 ( u s ed f o r */
_pg_s e t s t l e s et C s ty l es > : /* b o r d e r s ) -t h en s e t new . */

_pg_d e f a u l t c h a rt ( &en v , _P G_BA RCHART , _PG_P LA I N BARS ) ;

* c h a ra s e r s . N o t e t h a t t h e l i n e s ty l e s a re s e t i n t h e p a l e t t e , n o t
/ * Mod i fy p a l e t t e f o r d a ta l i n es , c o l o r s , f i l l p a t t e r n s , a n d

* i n t h e s ty l e s e t , s o t h a t on l y d a t a c o n n e c t o r s w i l l be a ff e c t ed .
*I
_pg_g e t p a l et t e ( p a l > :

!
I * Get d e fa u l t pa l et t e . */
pa l [ l J . p l ot c h a r = 1 6 ; I * S e t t o ASC I I 1 6 a nd 1 7 . */
pa l [ 2 J . p l ot c h a r = 1 7 ;


memcpy ( p l [ l ] . f i l l , f i l l l , 8 ) ; I * Copy f i l l ma s k s t o pa l ette . */
memcpy ( p 1 [ 2 ] . f i l l , f i l l 2 , 8 ) ;
pa l [ l ] . c � o r = 3 ; I * C h a n g e p a l ette c o l o r s . */
pa l [ 2 J . c o o r = 4 ;
p a l [ l ] . s t l e = 0xfcfc ; I * C h a n g e pa l ette l i n e s ty l es . */
pa l [ 2 ] . s t l e = 0x0303 ;
_p g_s e t p a l et t e ( pa l ) ; I * Put mod i f i ed pa l et t e . */
551 _pg_getpalette

I * M u l t i s e r i e s ba r c h a rt * /
s t rc py ( env . ma i n t i t l e . t i t l e , " L i t t l e Lea g u e Rec o r d s - C u s t omi zed " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l ue s ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch ( ) ;
_c l ea r s c reen ( _GC L EA RS C R E E N ) ;

I * M u l t i s e r i e s l i n e c h a rt * /
_p g_defa u l t c h a r t ( &env , _PG_L I N E CHART , _PG_P O I NTAN D L I N E ) ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " L i t t l e Lea g ue Records - C u s t omi zed " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l ues ,
T EAMS , MONTH S , MONTH S , teams ) ;

I * P r i nt l a b e l s . * /
_pg_h l a b e l c h a rt ( &env , ( s h o rt ) ( en v . c h a rtw i ndow . x 2 * . 75 ) ,
( s h o rt ) ( en v . c h a rtwi ndow . y 2 * . 10 ) ,
12 , " U p a nd up ! " ) ;
_pg_v l a be l c h a rt ( & e n v , ( s h o rt ) ( en v . c h a rtwi ndow . x 2 * . 75 ) ,
( s h o rt ) ( en v . c h a rtwi ndow . y 2 * . 45 ) ,
1 3 , " S l i d i n g down ! " ) ;
getch ( ) ;
_c l ea rs c reen ( _GC LEARSC R E E N l ;

_pg_r e s e t p a l et t e ( ) ; I * Restore d e fa u l t pa l ette *I


_pg_re s e t s ty l e s et ( ) ; I* and s ty l e s et . *I

/ * M u l t i s e r i e s ba r c h a rt * /
_pg_defa u l t c h a rt ( &en v , _PG_BARCHART , _PG_P LA I N BARS l ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " L i ttl e Lea g u e Rec o r d s - Defa u l t " l ;
_pg_c h a rtms ( &env , mon t h s , ( fl o a t _fa r * ) v a l ues ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch ( l ;
_c l ea r s c reen ( _GC LEARSC R E E N ) ;

I * M u l t i s e r i e s l i n e c h a rt * /
_pg_d efa u l t c h a r t ( &en v , _PG_L I N ECHART , _PG_PO I NTAN D L I N E ) ;
s t rcpy ( e n v . ma i n t i t l e . t i t l e , " L i t t l e L e a g u e Records - Defa u l t " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l u e s ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch < l ;

_s e t v i d e omod e ( _D E FAU LTMO D E ) ;


,
I

_pg_ge tyleset 558

Description
I Gets the current styleset.

I llinclude qigcbart.b>

void _far __pg_getstyleset( unsigned short _far *styleset );

styleset Pointer to current styleset

Remarks The __pg__getstyleset function retrieves the contents of the current styleset.

Return Value None.

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

See Also __pg_defaultchart, __pg_initchart, __pg_resetstyleset, __pg_setstyleset

Example See the example for __pg__getpalette.


559 _pg_ hlabelchart

Dllf:llpl/on Writes text horizontally on the screen.

#include <pgchart.h>

short _far _pg_hlabelchart( chartenv _far *env, short x, short y, short color,
char _far *label );

env Chart environment structure

x x-coordinate for text

y Pixel y-coordinate for text

color Color code for text


label Label text

Rematks The _pg_hlabelchart function writes text horizontally on the screen. The arguments x and
y are pixel coordinates for the beginning location of text relative to the upper-left comer of
the chart window.

Retum Value The _pg_hlabelchart functions return 0 if there were no errors. A nonzero value indicates
a failure.

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

S11 Alsa _pg_defaultchart, _pg_initchart, _pg_vlabelchart

Example See the example for _pg_getpalette.


560

Description I Initializes presentation graphics.

#include <pgchart.h>

I short _far _pg_initchart( void ) ;

R1marlcs The _pg_initchart function initializes the presentation-graphics package. I t initializes the
color and style pools, resets the chartline styleset, builds default palette modes, and reads
the presentation-graphics font definition from the disk. This function is required in all pro­
grams that use presentation graphics. The _pg_initchart function must be called before
any of the other functions in the presentation-graphics library.

The _pg_initchart function assumes a valid graphics mode has been established. There­
fore, it must be called only after a successful call to the library function _setvideomode.

I
R1lurn Va/UB The _pg_initchart functions return 0 if there were no errors. A nonzero value indicates a
failure.
!
CompallblllfYi 0 ANSI • DOS 0 OS/2 D UNIX D XENIX

SBB A/so _pg_defaultchart, _pg_getchardef, _pg_getpalette, _pg_getstyleset,


_pg_hlabelchart, _pg_resetpalette, _resetstyleset, _pg_setchardef, _pg_setpalette,
_pg_setstyleset, _pg_vlabelchart, _setvideomode

Examp/1 See the example for _pg_chart.


561 _pg resetpalette
_

Description Resets palette colors, line styles, and patterns to default values.

#include <pgchart.h>

short _far _pg_resetpalette( void );

Remarks The _pg_resetpalette function sets the palette colors, line styles, fill patterns, and plot
· characters for the palette to the default for the current screen mode.

The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.

Return Value The _pg_resetpalette function returns 0 if there were no errors. If the screen mode is not
valid, the value _BADSCREENMODE is returned.

Compat/bl/lty 0 ANSI • DOS 0 OS/2 0 UNIX 0 XENIX

See Also _pg_defaultchart, _pg_getpalette, _pg_initchart, _pg_setpalette

Example See the example for _pg_getpalette.


562

Dest:tlption i Resets styleset to default values.

#include <pgchart.h>

void _far _pg_resetstyleset( void );

Remarks The _pg_resetstyleset function reinitializes the styleset to the default values for the
current screen mode.

Return Value 1 None.

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

I
See Also i _pg_defaultchart, _pg__getstyleset, _pg_initchart, _pg_setstyleset

Example See the example for _pg__getpalette.


563 _ pg setchardel
_

· Description Sets the pixel bit map for the specified character.

#include <pgchart.h>

short _far _pg_setchardef( short charnum, unsigned char _far *chardef );

charnum ASCil number of character


chardef Pointer to an 8-by-8 bit map array for the character

Remarks The _pg_setchardef function sets the 8-by-8 pixel bit map for the character with the
ASCil number charnum. The bit map is stored in the chardef array.

Return Value The _pg_setchardef function returns 0 if there was no error. A nonzero value indicates an
error.

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

See Also _pg_defaultchart. _pg_getchardef, _pg_initchart


_pg_set alette 564

Dsscrlptlan Sets palette colors, line styles, and patterns.

#include <pgchart.h>

short _far _pg_setpalette( paletteentry _far *palette );

palette Pointer to first palette structure in array

Remarks The _pg_setpalette function sets palette colors, line styles, fill patterns, and plot charac­
ters for all palettes. The pointer palette points to an array of palette structures that contain
the desired palette values.
The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.

Return Value The _pg_setpalette function returns 0 if there were no errors. If the new palettes are not
valid, the value _BADSCREENMODE is returned.

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

See Also _pg_defaultchart, _pg__getpalette, _pg_initchart, _pg_resetpalette

Example See the example for _pg__getpalette.


666 _pg_setstyleset

D118t:rlpllon Sets the current styleset.

#include <pgchart.h>

void _far _pg_setstyleset( unsigned short _far *styleset ) ;

styleset Pointer to new styleset

llemal'lcs The _pg_setstyleset function sets the current styleset.

Retum Value None.

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

See Also _pg_defaultchart, _pg_getstyleset, _pg_initchart, _pg_resetstyleset

Example See the example for _pg_getpalette.


566

Descr/ptlan 1 Writes text vertically on the screen.

#include <pgchart.h>

short _far _pg_vlabelchart( chartenv _far •env, short x, short y, short color,
char _far *label ) ;

env Chart environment structure

x Pixel x coordinate for text

y Pixel y coordinate for text

color Color code for text

label Label text

Remades The _pg_vlabelchart function writes text vertically on the screen. The arguments x and y
are pixel coordinates for the beginning location of text relative to the upper-left corner of

Rslaml'allfJ
the chart window.

The _pg_vlabelchart function returns 0 if there were no errors. A nonzero value indicates


a failure.

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

See Alsa I _pg_defaultchart, _pg_hlabelchart, _pg_initchart

Example See the example for _pg_getpalette.


567 _pie Functions

Description Draw wedge-shaped figures.

#include <graph.h>

short _far _pie( short control, short xi, short yi, short x2, short y2, short .x3, short y3,
short x4, short "y4 );
short _far _pie_w( short control, double xi, double yi, double x2, double y2,
double .x3, double y3, double x4, double "y4 );
short _far _pie_wxy( short control, struct _wxycoord _far *pwxyi,
struct _wxycoord _far *pwxy2, struct _wxycoord _far *pwxy3,
struct _wxycoord _far*pwxy4 );

control Fill-control constant

xi , yl Upper-left comer of bounding rectangle

x2, y2 Lower-right comer of bounding rectangle

.x3, y3 Start vector

x4, "y4 End vector

pwxyl Upper-left comer of bounding rectangle

pwxy2 Lower-right comer of bounding rectangle

pwxy3 Start vector

pwxy4 End vector

Remades The _pie functions draw a pie-shaped wedge by drawing an elliptical arc whose center and
two endpoints are joined by lines.

The _pie function uses the view coordinate system. The center of the arc is the center of
the bounding rectangle specified by the view coordinate points (xi, yi ) and (x2, y2). The
arc starts where it intersects the vector defined by (.x3, y3) and ends where it intersects the
vector (x4, "y4).

The _pie_wxy and _pie_w functions use the window coordinate system. The center of the
arc is the center of the bounding rectangle specified by the window coordinate pairs pwxyi
and pwxy2 for _pie_wxy, and by the points (xi , yi ) and (x2, y2) for _pie_w. The arc starts
where it intersects the vector defined by pwxy3 or (.x3, y3) and ends where it intersects the
vector defined by pwxy4 or (x4, "y4).
_pie Fu,ctions I

568

The _wxycoord structure is defined in GRAPH.H and contains the following elements:

Element Description

double wx Window x coordinate

double wy Window y coordinate

The wedge is drawn using the current color moving in a counterclockwise direction. The
control parameter can be one of the following manifest constants:

Constant Action

_GFILLINTERIOR Fills the figure using the current color and fill mask
_GB ORDER Does not fill the figure

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


_floodfill function using the approximate center of the arc as the starting point and the cur­
rent color (set by _setcolor) as the boundary color.

Return Value
I These functions return a nonzero value if successful; otherwise, they return 0.

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

See Also I _arc functions, _ellipse functions, _floodfill, _getcolor, _lineto functions,
_rectangle functions, _setcolor, _setfdlmask

Exampm �-+--����-

1* PIE . C : r h i s p r o g r a m d raws a p i e - s h a ped f i g u re . * /

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


lti n c l u d e 4 o n i o . h >
f
#i n c l u d e < r a p h . h >
569 _pie Functions

v o i d ma i n ( )
(
I * F i nd a v a l i d g r a p h i c s mode . * /
i f ( ! _s et v i d eomod e C _MAX RESMODE )
exi t ( 1 ) ;

_p i e ( _GBORD E R , ·a 0 . 51/J , 241/J , 1 51/J , 241/J , 1 2 , rll , 1 51/J ) ;


getch C l ;

_s e t v i d eomod e ( _D E FAU LTMO D E ) ;


_pipe 570

D1Bt:rlpllan Creates a pipe for reading and writing.

#include <fcnd.h> For O_BINARY and O_TEXT definitions

#include <errno.h> errno definitions


#include <io.h> Prototype declaration

int _pipe( int *phandles, unsigned int psize, int textmode );

phandles[2] Array to hold read and write handles

psize Amount of memory to reserve

textmode File mode

R1matb A pipe is an artificial file-like 1/0 channel that a program can create and use to pass infor­
mation to other programs. A pipe is similar to a file in that it has a file pointer or a file de­
scriptor, or both, and can be read from or written to using the input and output functions of
the standard library. Unlike a file, a pipe does not represent a specific file or device. In­
stead, a pipe represents temporary storage in memory that is independent of the program's
own memory and is controlled entirely by the operating system.

Pipes may be used to pass information between programs. For example, the command pro­
cessor in OS/2 creates a pipe when executing a command such as

P ROGRAM l I P ROGRAM2

The standard output handle of PROGRAM! is attached to the pipe's write handle. The
standard input handle of PROGRAM2 is attached to the pipe's read handle. This elimi­
nates the need for creating temporary files to pass information to other programs.

The _pipe function creates a pipe. This function is similar to open but opens the pipe for
both reading and writing, returning two file handles instead of one. The program can either
use both sides of the pipe or close the one it does not need. This function typically opens a
pipe in preparation for linking it to a child process.

The _pipe function opens a pipe and returns two handles to the pipe in the phandles argu­
· ment. The element phandles[O) contains the read handle, and the element phandles[l ] con­
tains the write handle. Pipe file handles are used in the same way as other file handles.
(The low-level input and output functions read and write can read from and write to a
pipe.)

The psize argument specifies the amount of memory, in bytes, to reserve for the pipe.
571 _pipe

The textmode argument specifies the translation mode for the pipe. The manifest constant
O_TEXT specifies a text translation, and the constant O_BINARY specifies binary transla­
tion. (See fopen for a description of text and binary modes.) If the textmode argument is 0,
the _pipe function uses the default translation mode specified by the default-mode variable
_fmode.
In multithread programs, no locking is performed. The handles returned are newly opened
and should not be referenced by any thread until after the _pipe call is complete.

Under OS/2, a pipe is destroyed when all its handles have been closed. (If all read handles
on the pipe have been closed, writing to the pipe will cause an error.) All read and write
operations on the pipe wait until there is enough data or enough buffer space to complete
the 1/0 request.

Return Value The _pipe function returns 0 if successful. A return value of -1 indicates an error, and
errno is set to one of the following values:

Value Meaning

EMFILE No more file handles available (too many open files)


ENFILE System file table overflow

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

A similar function (pipe} is available in the XENIX and UNIX operating environments.

See Also cwait, _pclose, _popen

I * P I P E . C : T h i s p r o g r a m u s e s _p i pe to pa s s s t reams of text to
* c h i l d p r o c es s e s .
*I

#i n c l u d e <stdl i b . h>
#i n c l u d e <stdi o . h>
/Ii n c l u d e <i o . h>
#i n c l u d e <fcntl . h>
#i n c l u d e <proces s . h> I * _p i pe */
#i n c l u d e <ma t h . h >
_pipe 572

enum P I P E S ( READ , W R I T E } ; I * C on s t a nt s 0 a n d 1 for READ a n d W R I T E * /


#d e f i n e N U M P RO B L E M 8

v o i d ma i n ( i n t a rg c , c h a r *a rgv [ J
(
i nt h p i pe [ 2 J :
cha r h s t r [ 20 J :
i nt t e rms t a t , p i d , p robl em , c :

I * I f n o a rgumen t s , t h i s i s t h e pa rent . * /
i f ( a rg c 1 )
(
==

I * Open a s e t s o f p i pes . * /
i f ( _p i pe ( h p i pe , 2 5 6 , O_B I NARY ) == - 1 )
exi t ( 1 > :

I * C o n v e r t p i pe read h a n d l e to s t r i n g a n d pa s s a s a rg ument to
* s p a wned c h i l d . P ro g r a m spawns i t s e l f C a r g v [ 0 ] ) .
*I
i t oa C h p i p e [ READJ , h s t r , 1 0 > :
i f ( s p a w n l C P_NOWAI T , a rg v [ 0 ] , a r g v [ 0 ] , h s t r , N U L L == - 1 )
p r i ntf C " Spawn fa i l ed " > :

I * P u t p r o b l em i n w r i t e p i pe . S i n c e c h i l d i s r u n n i ng s i mu l t a neou s l y ,
* f i r s t s o l u t i o n s may b e done before l a s t p r o b l em i s g i ven .
*I
fo r e p robl em = 1 000 ; p r o b l em < = N U M P RO B L E M * 1000 ; p robl em += 1 000
(
p r i n t f C " Son , w h a t i s t h e s q u a re root of %d ? \ n " , p r o b l em > :
. w r i t e ( h p i p e [ W R I T E J , ( c h a r * ) &p r o b l em , s i zeo f C i n t ) l :

I * Wa i t u n t i l c h i l d i s d o n e proce s s i n g . * /
wa i t ( &te rms t a t > :
i f ( t e rms t a t & 0xff l
p r i n t f C " C h i l d fa i l ed \ n " > :

c l o s e ( h p i p e [ READ J > :
cl ose( hpi pe[WRITEJ > :
573 _pipe

I * I f t h e r e i s a n a rg ument , t h i s m u s t be t h e c h i l d . * /
el se
{
I * C o n v e rt pa s s ed s t r i ng h a n d l e t o i nt e g e r h a n d l e . * /
h p i p e [ READJ = a t o i C a rgv [ l ] ) ;

I * Rea d p robl em f rom p i pe a n d c a l c u l a t e s o l u t i on . * /


fo r ( c = 0 ; c < N U M P RO B L E M ; c++ )
{
rea d ( h p i p e [ READJ , ( c h a r * ) &p robl em , s i z eo f C i n t > ) ;
p r i n t f C " Da d , t h e s q u a re root of %d i s %3 . 2 f . \ n " ,
probl em , s q rt ( C d oubl e ) p robl em > ) ; ;

Output

Son , what i s the square root of 1000 ?


Da d , t h e s q u a re root o f 1 000 is 3 1 . 62 .
Son , w h a t i s t h e s q u a re root of 2000 ?
Son , w h a t i s t h e s q u a re root of 3000 ?
Dad , t h e s q u a re root of 2000 is 44 . 7 2 .
Son , w h a t i s t h e s q u a re root of 4000?
Dad , the s q u a re root of 3000 is 54 . 7 7 .
Son , w h a t i s t h e s q u a re root of 5000?
Dad , the s q u a r e root o f 4000 is 63 . 25 .
Son , w h a t i s t h e s q u a re root of 6000 ?
Dad , t h e s q u a r e root o f 5000 is 70 . 7 1 .
Son , w h a t i s t h e s q u a re root of 7000?
Dad , the s q u a r e root o f 6000 is 7 7 . 46 .
Son , w h a t i s t h e s q u a re root of 8000 ?
Dad , t h e s q u a re root of 7000 is 83 . 6 7 .
Dad , t h e s q u a r e root of 8000 is 89 . 44 .
_polygon Functions 574

Description Draw polygon shapes.

#include <graph.h>

short _far _polygon( short control, struct xycoord _far *points, short numpoints );
short _far _polygon_w( short control, double _far *points, short numpoints );
short _far _polygon_wxy( short control, struct _wxycoord _far *points,
short numpoints ) ;

control Fill flag

points Pointer to an array of structures defining the polygon

numpoints Number of points

Remarks The _polygon functions draw polygons. The border of the polygon is drawn in the current
color and line style. The _polygon routine uses the view coordinate system (expressed in
xycoord structures), and the _polygon_wxy and _polygon_w routines use real-valued win­
dow coordinates (expressed in _wxycoord structures and in pairs of double-precision float­
ing-point values, respectively).

The argument points is an array of xycoord or _wxycoord structures or pairs of doubles,


each of which specifies one of the polygon' s vertices. (For _polygon_w, points[O] and
points[ l ] specify the x and y coordinates, respectively, of the first point.) The argument
numpoints indicates the number of elements (the number of vertices) in the points array.
The control argument can be one of the following manifest constants:

Constant Action

_GFILLINTERIOR Fills the polygon using the current fill mask

_GBORDER Does not fill the polygon

The _setwritemode, _setlinestyle, and _setfillmask functions all affect the output from
the_polygon functions.

Return Value The _polygon functions return a nonzero value if the arc is successfully drawn; otherwise,
they return 0.

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


676 _polygon Functions

S11 A/Ba _ellipse functions, _floodfill, _lineto functions, _pie functions, _rectangle functions,
_setcolor, _setfillmask, _setlinestyle, _setwritemode

I * POLYGON . C : T h i s p r o g r a m d raws a s t a r - s h a ped pol ygon . * /

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

#d ef i n e P I 3 . 1 4 1 5

v o i d ma i n ( )
(
s h o rt s i d e , rad i u s = 90 , x = 0 , y = 0 ;
doubl e radi a n s ;
s t ruct xyc o o r d pol y s i d e [ 5 J ;
s t ruct v i d e o c on f i g v c ;

I * F i n d a v a l i d g r a p h i c s mode . * /
i f ( ! _s et v i d eomode ( _MA X R ESMODE
exi t ( 1 ) ;

_ge t v i de o c o n f i g ( & v c ) ;
_s e t v i ew o r g ( v c . n umx p i x e l s I 2 , v c . n umyp i x e l s I 2 ) ;

I * C a l c u l a t e p o i n t s o f s t a r e v e ry 144 d e g rees , t h e n connect t h em . * /


f o r ( s i d e = 0 ; s i d e < 5 ; s i d e++ )
(
ra d i a n s = 144 * P I / ' 180 ;
pol y s i d e [ s i de J . x c o o r d = x + ( s h o rt ) ( c o s ( s i de * r a d i a n s * radi us ) ;
pol y s i d e [ s i de J . yc o o rd = y + C s h o rt ) ( s i n ( s i de * r a d i a n s * radi us ) ;
)
_po l ygon ( _G F I L L I NT E R I O R , po l y s i de , 5 ) ;

getc h ( ) ;
_s e t v i d e omod e ( _O E FAU LTMOD E ) ;
_papen 576

Dest:rlptlon Creates a pipe and executes a command.

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

FILE *_popen( char *command, char *mode );

command Command to be executed

mode Mode of returned stream

Remarks The _popen function creates a pipe and asynchronously executes a child copy of the com­
mand processor with the specified command string command. See _pipe for a general dis­
cussion of pipes in OS/2. The character string mode specifies the type of access requested,
as follows:

Description
" r" The calling process can read the child command's standard
output via the returned stream.
" w" The calling process can write to the child command's standard
input via the returned stream.
" b" Open in binary mode.
" t" Open in text mode.

See Section 2. 7, "Input and Output," for a discussion of text and binary modes.

Retum Value The _popen function returns a stream associated with one end of the created pipe. The
other end of the pipe is associated with the child command's standard input or standard out­
put. If an error occurs, NULL is returned.

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

A similar function (popen) is available in the XENIX and UNIX operating environments.

See Also _pclose, _pipe

I * P O P E N . C : T h i s p r o g r a m u s e s _popen a n d _pc l o s e t o rec e i v e a s t ream


* of text f rom a c h i l d s y s t em p r o c e s s .
*I
577 _papen

#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 ( )
(
cha r buffer [ 128J ;
FI LE * c h kd s k ;

I * Run C H K D S K s o t h a t i t w r i t e s i t s output t o a p i pe . Open p i pe


* w i t h r e a d text a tt r i b u t e s o that we can r e a d i t l i ke a text f i l e .

_popen ( " d i r po* . c I s o rt I more • , " rt • ) ) == N U L L )


*/
i f ( C c h kd s k =

exi t ( 1 ) ;

I * Read p i pe u n t i l end of fi l e . End of f i l e i n d i c a t e s t h a t CHKDSK


* c l o s e d i t s s t a n d a rd out ( p roba bl y mea n i n g it t e rmi n a t ed ) .
*I
w h i l e ( ! fe o f C c h kd s k > >
(
i f ( fget s ( buffe r , 1 28 , c h kd s k ) ! = N U L L )
p r i n t f ( buffer ) ;

I * C l o s e p i p e a nd p r i nt retu rn v a l u e of C H K DS K . * /
p r i n t f ( " \ n C h i l d r e t u r n e d %d \ n " , _pc l o s e C c h kd s k ) ) ;

Output

3 Fi l e ( s ) 1 2683264 bytes f r e e
D i r e c t o ry o f C : \ L I B R E F
T h e v o l ume l a b e l i n d r i v e C i s 052 .
P O L Y GO N C 921 6 - 14-89 6 : 51p
POPEN C 845 6 - 1 9 - 89 2 : 48p
POW C 190 6 - 1 3 - 89 6 : 07 p

C h i l d r e t u rned 0
paw Functions 578

DllBt:llptlan Calculate x raised to the power of y.

#include <math.h>

double pow( double x, double y ) ;


long double powl( long double x, long double y ) ;

x Number to be raised

y Power of x

Remalb The pow and powl functions compute x raised to the power of y.
The powl function is the 80-bit counterpart, and it uses an 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.

Retum Value The pow and powl functions return the value of � . If x is not 0.0 and y is 0.0, pow and
powl return the value 1 . If x is 0.0 and y is negative, pow and powl set errno to EDOM
and return 0.0. If both x and y are 0.0, or if x is negative and y is not an integer, the func­
tion prints a DOMAIN error message to stderr, sets ermo to EDOM, and returns 0.0. If an
overflow results, the function sets ermo to ERANGE and returns ±HUGE VAL. No mes-
-

sage is printed on overflow or underflow. ·

The pow function does not recognize integral floating-point values greater than 264, such
as 1 . 0 E 1 00 .

Compatibility pow

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

powl

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

See Also exp, log functions, sqrt

I * P OW . C * /
#i n c l u d e <ma t h . h >
#i n c l ude < s t d i o . h>
579 pow Functions

v o i d ma i n ( )
{
doubl e x = 2.0, y = 3.0, z;

z - pow ( x , y ) ;
p r i n t f ( " % . l f t o t h e p owe r of % . l f i s % . l f \ n " , x, y, z ) ;

Output

2 . 0 t o t h e powe r of 3 . 0 i s 8 . 0
printf 580

Description Prints formatted output to the standard output stream.

#include <Stdio.h>

int printf( const char *format [, 01xume11t]) ... );

format Format control

01:�ument Optional arguments

Remarks The printf function formats and prints a series of characters and values to the standard out­
put stream, stdout. The format argument consists of ordinary characters, escape sequen­
ces, and (if arguments follow format) format specifications. The ordinary characters and
escape sequences are copied to stdout in order of their appearance. For example, the line

p r i n t f ( " L i ne o n e \ n \ t \ t l i n e two \ n " ) ;

produces the output

L i n e one
L i ne two

If arguments follow the format string, the format string must contain specifications that de­
termine the output format for the arguments.

Format specifications always begin with a percent sign (%) and are read left to right.
When the first format specification (if any) is encountered, the value of the first argument
afterformat is converted and output accordingly. The second format specification causes
the second argument to be converted and output, and so on. If there are more arguments
than there are format specifications, the extra arguments are ignored. The results are unde­
fined if there are not enough arguments for all the format specifications.

A format specification, which consists of optional and required fields, has the following
form:
% [f7ags]) [width]) [.precision]) [ { F I N I h I 1 1 L }])type
Format Specification Fields
Each field of the format specification is a single character or a number signifying a particu­
lar format option. The simplest format specification contains only the percent sign and a
type character (for example, % s ) . The optional fields, which appear before the type charac­
ter, control other aspects of the formatting. The fields in a printf format specification are
described in the following list:
581 print!

Field Description

type Required character that determines whether the associated ar­


gument is interpreted as a character, a string, or a number.
(See Table R.2.)

flags Optional character or characters that control justification of


output and printing of signs, blanks, decimal points, and octal
and hexadecimal prefixes. (See Table R.3.) More than one
flag can appear in a format specification.
width Optional number that specifies minimum number of charac­
ters output.

precision Optional number that specifies maximum number of charac­


ters printed for all or part of the output field, or minimum
number of digits printed for integer values. (See Table R.4.)
F, N Optional prefixes that refer to the "distance" to the object
being printed (near or far).
F and N are not part of the ANSI definition for printf. They
are Microsoft extensions that should not be used if ANSI
portability is desired.

h, I, L Optional prefixes that determine the size of the argument ex­


pected, as shown below:

Prefix Use

h Used with the integer types d, i, o, x, and X


to specify that the argument is short int, or
with u to specify short unsigned int. If
used with % p, it indicates a 1 6-bit pointer.

Used with d, i, o, x, and X types to specify


that the argument is long int, or with u to
specify long unsigned int; also used with
e, E, f, g, and G types to specify double
rather than float. If used with % p, it indi­
cates a 32-bit pointer.

L Used with e, E, f, g, and G types to specify


long double.

If a percent sign is followed by a character that has no meaning as a format field, the char­
acter is copied to stdout. For example, to print a percent-sign character, use %%.
prinff 582

1}tpe Field CharactetS

The type character is the only required fonnat field for the printf function; it appears after
any optional fonnat fields. The type character detennines whether the associated argument
is interpreted as a character, a string, or a number. (See Table R.2.)

Table R.2 Type Characters for printf

Character Type Output Format

d int Signed decimal integer.


int �igned decimal integer.
u int Unsigned decimal integer.
0 int Unsigned octal integer.
x int Unsigned hexadecimal integer, using "abcdef."
x int Unsigned hexadecimal integer, using "ABCDEF."
f double Signed value having the form [-]dddd.dddd, where dddd is one or
more decimal digits. The number of digits before the decimal point
depends on the magnitude of the number, and the number of digits
after the decimal point depends on the requested precision.

e double Signed value having the form [-]d.dddd e [sign]ddd, where d is a


single decimal digit, dddd is one or more decimal digits, ddd is ex-
actly three decimal digits, and sign is + or -.
E double Identical to the e format, except that E, rather than e, introduces the
exponent.
g double Signed value printed in f or e format, whichever is more compact for
the given value and precision. The e format is used only when the
exponent of the value is less than -4 or greater than or equal to the
precision argument. Trailing zeros are truncated, and the decimal
point appears only if one or more digits follow it
G double Identical to the g format, except that G, rather than g, introduces the
exponent (where appropriate).
c int Single character.
s String Characters printed up to the first null character ('\O') or until the
precision value is reached.
n Pointer to Number of characters successfully written so far to the stream or
· integer buffer; this value is stored in the integer whose address is given as
the argument.
p Far pointer Prints the address pointed to by the argument in the form xxxr.yyyy,
to void where xox is the segment and yyyy is the offset, and the digits x and
y are uppercase hexadecimal digits; %hp indicates a near pointer
and prints only the offset of the address.
583 printf

Rag Directives

The first optional field of the format specification is flag. A flag directive is a character
that justifies output and prints signs, blanks, decimal points, and octal and hexadecimal pre­
fixes. More than one flag directive may appear in a format specification. (See Table R.3.)

Table R.3 Flag Characters for printf

Flag Meaning Default

Left justify the result within the given Right justify.


field width.

+ Prefix the output value with a sign Sign appears only for negative
(+ or -) if the output value is of a signed values (-).
signed type.

0 If width is prefixed with 0, zeros are No padding.


added until the minimum width is
reached. If 0 and - appear, the 0 is
ignored. If 0 is specified with an
integer format (i, u , x, X, o, d), the
0 is ignored.
blank (' ') Prefix the output value with a blank if No blank appears.
the output value is signed and positive;
the blank is ignored if both the blank
and + flags appear.

# When used with the o, x, or X format, No blank appears.


the # flag prefixes any nonzero output
value with 0, Ox, or OX, respectively.

When used with the e, E, or f format, Decimal point appears only if


the # flag forces the output value to con­ digits follow it.
tain a decimal point in all cases.

W hen used with the g or G format, the Decimal point appears only if
# flag forces the output value to contain digits follow it. Trailing zeros are
a decimal point in all cases and pre­ truncated.
vents the truncation of trailing zeros.

Ignored when used with c, d, i, u , or s.


printf 584

Width Specification

The second optional field of the format specification is the width specification. The width
argument is a non-negative decimal integer controlling the minimum number of characters
printed. If the number of characters in the output value is less than the specified width,
blanks are added to the left or the right of the values-depending on whether the
- flag (for left justification) is specified-until the minimum width is reached. If width is
prefixed with O,' zeros are added until the minimum width is reached (not useful for left­
justified numbers).

The width specification never causes a value to be truncated. If the number of characters in
the output value is greater than the specified width, or width is not given, all characters of
the value are printed (subject to the precision specification).

The width specification may be an asterisk (*), in which case an int argument from the
argument list supplies the value. The width argument must precede the value being for­
matted in the argument list. A nonexistent or small field width does not cause a truncation
of a field; if the result of a conversion is wider than the field width, the field expands to
contain the conversion result.

Precision Specification

The third optional field of the format specification is the precision specification. It speci­
fies a non-negative decimal integer, preceded by a period (.), which specifies the number
of characters to be printed, the number of decimal places, or the number of significant
digits. (See Table R.4.) Unlike the width specification, the precision specification can
cause truncation of the output value, or rounding in the case of a floating-point value. If
precision is specified as zero and the value to be converted is zero, the result is no charac­
ters output, as shown below:

p r i n t f ( " % . 0d " , 0 ) ; / * N o c h a r a c t e r s output * /

The precision specification may be an asterisk (•), i n which case an int argument from the
argument list supplies the value. The precision argument must precede the value being for­
matted in the argument list.

The interpretation of the precision value and the default when precision is omitted depend
on the type, as shown in Table R.4.
585 printf

Table R.4 How printf Precision Values Affect Type

Type Meaning Default

d The precision specifies the minimum num­ If precision is 0 or omitted entirely, or if


ber of digits to be printed. If the number the period (.) appears without a number
u of digits in the argument is less than following it, the precision is set to 1 .
0 precision, the output value is padded on
x the left with zeros. The value is not trun­
x cated when the number of digits exceeds
precision. I

e The precision specifies the number of Default precision is 6; if precision is 0 or


E digits to be printed after the decimal the period (.) appears without a number
point. The last printed digit is rounded. following it, no decimal point is printed.
f The precision value specifies the number Default precision is 6; if precision is 0, or
of digits after the decimal point If a deci­ if the period (.) appears without a number
mal point appears, at least one digit following it, no decimal point is printed.
appears before it The value is rounded to
the appropriate number of digits.
g The precision specifies the maximum Six significant digits are printed, with any
G number of significant digits printed. trailing zeros truncated.
c The precision has no effect. Character is printed
s The precision specifies the maximum Characters are printed until a null charac­
number of characters to be printed. Char­ ter is encountered.
acters in excess of precision are not
printed.

If the argument corresponding to a floating-point specifier is infinite, indefinite, or not a


number (NAN), the printf function gives the following output:

Value Output

+ infinity 1.#1.NFrandom-digits
- infinity -l.#INFrandom-digits
Indefinite digit.#INDrandom-digits
NAN digit.#NANrandom-digits
printf 586

Sia and Dlstant:e Specification

For printf, the format specification fields F and N refer to the "distance" to the object
being read (near or far), and h and I refer to the "size" of the object being read ( 1 6-bit
short or 32-bit long). The following list clarifies this use of F, N, h, I, and L:

Program Code Action

printf (" %Ns"); Print near string

, printf (" %Fs" ); Print far string

printf (" %Nn"); Store char count in near int

printf (" %Fn" ); Store char count in far int

printf (" % hp"); Print a 16-bit pointer (xxxx')

printf (" % Ip" ); Print a 32-bit pointer (xxxx:x)xu

printf (" %Nhn"); Store char count in near short int

printf (" %Nin"); Store char count in near long int

printf (" %Fhn"); Store char count in far short int

printf (" %Fin"); Store char count in far int

The specifications " %hs" and " %Is" are meaningless to printf. The specifications
" %Np" and " %Fp" are aliases for " %hp" and " %Ip" for the sake of compatibility with
Microsoft C version 4.0.

Relum Value The printf function returns the number of characters printed, or a negative value in the
case of an error.

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


587 printf

See Also fprintf, scanf, sprintf, vfprintf, vprintf, vsprintf

I * P R I NT F . C i l l u s t ra t e s output f o rma t t i ng w i t h p r i n t f . * /

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

v o i d ma i n ( )
(
char c h = ' h ' , * s t r i n g = " c omput e r " ;
i nt c o u n t = - 9 2 34 ;
d o u b l e fp = 2 5 1 . 7 366 ;

I * Di spl ay i ntegers . */
p r i n t f C " I nt e g e r fo rma t s : \ n "
" \ t D ec i ma l : % d J u st i f i ed : % . 6d U n s i gned : % u \ n " ,
c o u n t , c o u n t , count , c o u n t ) ;

p r i n t f ( " D ec i ma l %d a s : \ n \ t H ex : % X h C h e x : 0x%x Oct a l : %0\ n " ,


c o u n t , c o u n t , count , count ) ;

I * D i s p l a y i n d i fferent r a d i x e s . * /
p r i n t f ( " D i g i t s 1 0 equa l : \ n \ tHex : % i Oct a l : % i Dec i ma l : % i \ n " ,
0 x l 0 , 0 1 0 , 10 ) ;

I * Di spl ay cha racters . */


pri ntfC " C h a racters in fi el d : \ n%10c %5c \n " , ch , ch ) ;

I * D i s p l ay s t r i n g s . * /
p r i n t f ( " St r i n g s i n f i e l d : \ n % 2 5 s \ n % 2 5 . 4 s \ n " , s t r i n g , s t r i n g ) ;

I * D i s p l a y rea l n umbe r s . * /
p r i n t f ( " Rea l n umbe r s : \ n \ t%f % . 2f %e % E \ n " , fp , fp , fp , fp ) ;

/* D i s p l a y p o i n t e r s . */
p r i n t f ( " Add r e s s a s : \ n \ tDefa u l t : %p Nea r : % N p Fa r : % F p \ n " ,
& c o u n t , ( i n t _n ea r * ) &count , ( i n t _fa r * ) &c o u n t ) ;

/ * Count c h a r a c t e r s p r i nted . * /
p r i n t f C " D i s p l a y t o h e re : \ n " ) ;
p r i n t f ( " 1 234567890 1 2 3456%n7890 1 234567890 \ n " , &count ) ;
p r i ntf ( " \ t N umber d i s p l ayed : %d \ n \ n " , c o u n t ) ;
printf 588

Output

I n t e g e r f o rma t s :
Dec i ma l : - 9 234 J u s t i f i ed : - 009234 U n s i gned : 56302
D ec i ma l - 9 234 a s :
Hex : D B E E h C h e x : 0xdbee Oct a l : 1 5 5 7 5 6
D i g i t s 1 0 e q ua l :
Hex : 1 6 Oct a l : 8 Dec i ma l : 1 0
Cha racters i n fi el d :
h h
Stri ngs i n fi el d :
comp u t e r
c omp
Rea l n umbe r s :
2 5 1 . 7 36600 251 . 74 2 . 5 1 7 3 66e+002 2 . 5 1 7 3 6 6 E+002
Add r e s s a s :
Defa u l t : 141C N e a r : 141C Fa r : 0087 : 14 1 C
D i s p l ay t o h e r e :
1 2 34567890 1 2 34567 890 1 234567890
N umbe r d i s p l ayed : 1 6
589 pule, putchar

Description Writes a character to a stream (putc) or to stdout (putchar).

#include <Stdio.h>

int putc( int c, FILE *stream );


int putchar( int c );

c Character to be written
stream Pointer to FILE structure

Remarks The putc routine writes the single character c to the output stream at the current position.
The putchar routine is identical to putc(c, stdout).

These routines are implemented as both macros and functions. See Section 1 .4, "Choosing
Between Functions and Macros," for a discussion of how to select between the macro and
function forms.

Return Value The putc and putchar routines return the character written, or EOF in the case of an error.
Any integer can be passed to putc, but only the lower 8 bits are written.

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

See Also fputc, fputchar, getc, getchar

I * PUTC . C : T h i s p r o g r a m u s e s putc to w r i te buffer to a s t r e a m .


* I f a n e r r o r o c c u r s , t h e p r o g r a m w i l l s t o p before w r i t i ng t h e
* en t i re buffe r .
*I

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

v o i d ma i n ( )
{
FI LE *stream ;
c h a r *p , buffe r [ ] " Th i s i s t h e l i n e o f output \ n " ;
i nt ch ;
putc, putchar 590

I * Ma k e s t a n d a rd out t h e s t ream a n d w r i t e t o i t . * /
s t re a m = s t d o u t ;
f o r ( p = b uffer ; ( c h ! = EO F ) && ( *p ! = ' \ 0 ' ) ; p++ )
c h = putc ( *p , s t re a m ) ;

Output

T h i s i s t h e l i n e of o u t p u t
591 putch

Description Writes a character to the console.

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

int putch( int c );

c Character to be output

Remarks The putch function writes the character c directly (without buffering) to the console.

Return Value The function returns c if successful, and EOF if not.

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

See Also cprintf, getch, getche

I * GETCH . C : T h i s p r o g r a m rea d s c h a r a c t e r s f rom 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 u d e < c o n i o . h>
#i n c l u d e <ctype . h >

v o i d ma i n ( )
(
i nt c h ;

c p u t s ( " Ty p e ' Y ' when f i n i s h ed typi n g key s : • ) ;


do
(
c h = getch ( ) ;
c h = touppe r ( c h ) ;
whi l e ( ch ! = ' Y ' ) ;

p ut c h ( c h ) ;
put c h ( ' \ r ' ) ; I * Ca rri age return */
putc h ( ' \ n ' ) ; I * L i n e feed */

Output

Typ e ' Y ' w h e n f i n i s h ed typ i n g key s : Y


putenv 592

Description Creates new environment variables.

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

int putenv( char *envstring );

envstring Environment-string definition

Remarks The putenv function adds new environment variables or modifies the values of existing en­
vironment variables. Environment variables define the environment in which a process ex­
ecutes (for example, the default search path for libraries to be linked with a program).

The envstring argument must be a pointer to a string with the form

varname=string
where varname is the name of the environment variable to be added or modified and string
is the variable's value. If varname is already part of the environment, its value is replaced
by string; otherwise, the new varname variable and its string value are added to the en­
vironment. A variable can be set to an empty value by specifying an empty string.

This function affects only the environment that is local to the currently running process; it
cannot be used to modify the command-level environment. When the currently running
process terminates, the environment reverts to the level of the parent process (in most
cases, the operating system level). However, the environment affected by putenv can be
passed to any child processes created by spawn, exec, system, or (in OS/2 only) _popen,
and these child processes get any new items added by putenv.

Never free a pointer to an environment entry, because the environment variable will then
point to freed space. A similar problem can occur if you pass putenv a pointer to a local
variable, then exit the function in which the variable is declared.

The putenv function operates only on data structures accessible to the run-time library and
not on the environment "segment" created for a process by DOS or OS/2.

Note that environment-table entries must not be changed directly. If an entry must be
changed, use putenv. To modify the returned value without affecting the environment
table, use strdup or strcpy to make a copy of the string.
The getenv and putenv functions use the global variable environ to access the environ­
ment table. The putenv function may change the value of environ, thus invalidating the
envp argument to the main function. Therefore, it is safer to use the environ variable to
access the environment information.

Return Value The putenv function returns 0 if it is successful. A return value of -1 indicates an error.
593 putenv

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

Sse A/sa getenv

I * G E T E N V . C : T h i s p r o g r a m u s e s getenv to ret r i eve t h e L I B e n v i ronment


* v a r i a bl e and then uses putenv t o c h a nge i t to a new v a l u e .
*/

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

ma i n ( )
(
c h a r *l i b va r ;

I * Get t h e v a l ue of t h e L I B e n v i ronment v a r i a b l e . * /
l i bv a r = geten v < " L I B " > :
i f ( l i bva r I = 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 bva r ) :

I * Attempt t o c h a n g e p a t h . Note t h a t t h i s on l y a ffects t h e en v i ronment


* v a r i a b l e o f t h e c u r r ent p r o c e s s . T h e c omma nd p r o c e s s o r ' s e n v i ronment
* i s not c h a n g ed .
*I
puten v ( " L I B=c : \ \my l i b ; c : \ \y o u r l i b " > :

I * Get new v a l u e . * /
l i b va r = geten 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 bv a r > :

Output

Ori gi nal L I B vari abl 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
_putimage Functions 594

Description Retrieve images from a buffer.

#include <graph.h>

void _far _putimage( short x, short y, char _huge *image, short action );
void _far _putimage_w( double wx, double wy, char _huge *image, short action );

x, y Position of upper-left comer of image

image Stored image buffer

action Interaction with existing screen image

wx, wy Position of upper-left comer of image

Remarks The _putimage function transfers to the screen the image stored in the buffer that image
points to.
In the _putimage function, the upper-left comer of the image is placed at the view coordi­
nate point (x, y). In the _pu timage_w function the upper-left comer of the image is placed
,

at the window coordinate point (wx, wy).

The action argument defines the interaction between the stored image and the one that is
already on the screen. It may be any one of the following manifest constants (defined in
GRAPH.ff):

Constant Meaning

_GAND Transfers the image over an existing image on the screen. The
resulting image is the logical-AND product of the two images:
points that had the same color in both the existing image and
the new one will remain the same color, while points that have
different colors are joined by logical-AND.

_GOR Superimposes the image onto an existing image. The new


image does not erase the previous screen contents.
_GPRESET Transfers the data point-by-point onto the screen. Each point
has the inverse of the color attribute it had when it was taken
from the screen by _getimage, producing a negative image.
595 _putimage Functions

_GPSET Transfers the data point-by-point onto the screen. Each point
has the exact color attribute it had when it was taken from the
screen by _getimage.

_GXOR Causes the points on the screen to be inverted where a point


exists in the image buffer. This behavior is exactly like that of
the cursor: when an image is put against a complex back­
ground twice, the background is restored unchanged. This al­
lows you to move an object around without erasing the
background. The _GXOR constant is a special mode often
used for animation.

Return Value None.

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

See Also _getimage, _imagesize

Example See the example for _getimage.


puts 596

Description Writes a string to stdout.

#include <stdio.h>

int puts( const char *string );

string String to be output

Remarks The puts function writes string to the standard output stream stdout, replacing the string' s
terminating null character ('\0') with a newline character (\n) i n the output stream.

Return Value The puts function returns a nonnegative value if it is successful. If the function fails, it
retums EOF.

Compat/blllty m ANSI • DOS • OS/2 • UNIX • XEN IX

See Also fputs, gets

I * PUTS . C : T h i s p r o g r a m u s e s p u t s to w r i t e a s t r i n g to s tdout . * /

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

v o i d ma i n ( )
{
p ut s ( " H e l l o w o r l d f r om p u t s ! " > :

Output

H e l l o w o r l d f r om p u t s !
691 putw

DllSCtlptlon Writes an integer to a stream .

#include <Stdio.h>

int putw( int binint, FILE *stream );

binint Binary integer to be output

stream Pointer to FILE structure

Remarks The putw function writes � binary value of type int to the current position of stream. The
putw function does not affect the alignment of items in the stream, nor does it assume any
special alignment.

The putw function is provided primarily for compatibility with previous libraries. Note
that pqrtability problems may occur with putw, since the size of an int and ordering of
bytes within an int differ across systems.

Rstum Va/us The putw function returns the value written. A return value of EOF may indicate an error.
Since EOF is also a legitimate integer value, ferror should be used to verify an error.

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

S11 Also getw

I * PUTW . C : T h i s p r o g r a m u s e s putw to w r i te a word to a s t ream ,


* t h e n perfo rms a n e r r o r c h ec k .
*/

#i n c l u d e < s td i o . h >
#i ncl ude <stdl i b . h>

v o i d ma i n ( )
{
F I L E * s t r ea m :
u n s i gned u :

i f ( ( s t r e a m = fopen ( " d a t a . out " , " wb " ) ) � N U L L l


ex i t ( 1 > :
fo r e u 0 : u < 1 0 : u++ >
{
=

putw C u + 0 x 2 1 3 2 , s t d o u t ) ;
putw ( u + 0 x 2 1 3 2 , s t ream > : / * W r i t e word to s t re a m . * /
putw 598

i f ( fe r r o r C s t ream ) ) I * Ma ke e r r o r c h ec k . * /
(
p r i n t f ( " p utw fa i l ed " > :
c l ea re r r < s t ream > :
exi t ( 1 > :

}
p r i n t f ( " \ nWrote ten word s \ n " > :
f c l o s e ( s t ream > :

Output

213!4!51617 !8!9! : ! ; !
Wrote ten w o r d s
599 qsort

Dut:r/ptlan Perfonns a quick sort.

#include <Stdlib.h> For ANSI compatibility

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

void qsort( void *base, size_t num, size_t width,


int( *compare ) ( const void *elem], const void *elem2 ) );

base Start of target array


num Array size in elements
width Element size in bytes
compare Comparison function

elem] Pointer to the key for the search

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

Rematits The qsort function implements a quick-sort algorithm to sort an array of num elements,
each of width bytes. The argument base is a pointer to the base of the array to be sorted.
The qsort function overwrites this array with the sorted elements.

The argument compare is a pointer to a user-supplied routine that compares two array ele­
ments and returns a value specifying their relationship. The qsort function calls the
compare routine one or more times during the sort, passing pointers to two array elements
on each call:

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


The routine must compare the elements, then return one of the following values:

Value Meaning

<0 eleml less than elem2


=0 eleml equivalent to elem2
>0 elem] greater than elem2

The array is sorted in increasing order, as defined by the comparison function. To sort an
array in decreasing order, reverse the sense of "greater than" and "less than" in the com­
parison function.
qsart 600

Return Value None.

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

See Also bsearch, lsearch

I * OSORT . 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 pa rameters a n d


* u s e s q s o rt to s o rt t h em . I t t h e n d i s p l a y s t h e s o r ted a rguments .
*I

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

i nt comp a r e < c h a r **a r g l , c h a r **a rg2 ) ; / * P rototype * /

v o i d ma i n < i nt a r g c , c h a r **a rgv )


{
i nt i ;

I * E l i mi n a t e a rg v [ 0 ] f rom s o rt : * /
a rg v++ ;
a rg c- :

I * S o rt rema i n i n g a rg s u s i n g Q u i c ks o rt a l g o r i t h m : * /
q s o rt { < v o i d * l a rg v , C s i z e_t ) a rgc , s i zeof { c h a r * ) , comp a re ) ;

I * O u t p u t s o rted l i s t : */
fo r { i = 0 : i < a rg c : ++i
p r i n t f { " %s • , a rg v [ i ] > :
pri ntf { " \ n " > :

i n t compa re < c h a r **a rg l , c h a r **a rg2


{
I * Comp a re a l l of b o t h s t r i n g s : * /
ret u r n s t rcmpi { *a r g l , * a rg2 ) ;

Output

[ C : \ L I B R E F ] q s ort e v e ry good boy d e s e r v e s f a v o r


b o y d e s e r v e s e v e ry fa v o r good
601 raise

Description Sends a signal to the executing program.

#include <Signal.h>

int raise( int sig );

sig Signal to be raised

Remarks The raise function sends sig to the executing program. If a signal-handling routine for sig
has ben installed by a prior call to signal, raise causes that routine to be executed. If no
handler routine has been installed, the default action (as listed below) is taken.
The signal value sig can be one of the following manifest constants:

Signal Meaning Default

SIGABRT Abnormal termination. Terminates the calling pro­


gram with exit code 3.
SIGBREAK CTRL+ BREAK interrupt. Terminates the calling pro­
gram with exit code 3.
SIGFPE Floating-point error. Terminates the calling
program.
SIGILL Illegal instruction. This signal Terminates the calling
is not generated by DOS or program.
OS/2, but is supported for
ANSI compatibility.
SIGINT CTRL+ c interrupt. Issues INT23H.
SIGSEGV Illegal storage access. This Terminates the c alling
signal is not generated by program.
DOS or OS/2, but is supported
for ANSI compatiblity.

the program. This signal is not


SIGTERM Termination request sent to Ignores the signal.

generated by DOS or OS/2,


but is supported for ANSI
compatibility.
SIGUS RI User-defined signals. Ignores the signal.
SIGUSR2
SIGUSR3
raise 602

Return Value If successful, the raise function returns 0. Otherwise, it returns a nonzero value.

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

See Also abort. signal

Example See the example for signal.


603 rand

Description Generates a pseudorandom number.

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

int rand( void );

Remarks The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. The
srand routine can be used to seed the pseudorandom-number generator before calling
rand.

Return Value The rand function returns a pseudorandom number, as described above. There is no error
return.

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

See Also srand

I * RAN D . C : T h i s p r o g r a m s ee d s t h e r a n d om - n umber g e n e r a t o r w i t h t h e
* t i me , t h en d i s p l ays 20 r a n d om i n t e g e r s .
*I

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


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

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

I * Seed t h e r a n d om- n umber g en e r a t o r w i t h c u r rent t i me s o t h a t


* t h e numb e r s w i l l b e d i fferent e v e ry t i me we run .
*I
s r a n d ( C u n s i g n e d ) t i me ( N U L L ) ) ;

I * D i s p l ay 10 n umbe rs . * /
fo r ( i = 0 ; i < 10 ; i ++ )
p r i n t f ( • %6d \ n " , r a n d ( ) ) ;
rand 604

Output

1 947 1
1 6395
8268
1 5 58 2
6489
28356
27042
5276
23070
10930
605 read

Daer/pt/an Reads data from a file.

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

int read( int handle, void *buffer, unsigned int count );

handle Handle referring to open file


buffer Storage location for data

count Maximum number of bytes

Remarks The read function attempts to read count bytes into buffer from the file associated with
handle. The read operation begins at the current position of the file pointer associated with
the given file. After the read operation, the file pointer points to the next unread character.

Return Value The read function returns the number of bytes actually read, which may be less than count
if there are fewer than count bytes left in the file, or if the file was opened in text mode
(see below). The return value 0 indicates an attempt to read at end-of-file. The return value
-1 indicates an error, and errno is set to the following value:

Value Meaning
EBADF The given handle is invalid; or the file is not open for reading;
or (DOS versions 3.0 and later and OS/2 only) the file is
locked.

If you are reading more than 32K (the maximum size for type int) from a file, the return
value should be of type unsigned int (see the example that follows). However, the maxi­
mum number of bytes that can be read from a file in one operation is 65,534, since 65,535
(or OxFFFF) is indistinguishable from -1 , and therefore cannot be distinguished from an
error return.

If the file was opened in text mode, the return value may not correspond to the number of
bytes actually read. When text mode is in effect, each carriage-return-line-feed (CR-LF)
pair is replaced with a single line-feed character. Only the single line-feed character is
counted in the return value. The replacement does not affect the file pointer.

Note that under DOS and OS/2, when files are opened in text mode, a CTRL+Z character is
treated as an end-of-file indicator. When the CTRL+Z is encountered, the read terminates,
and the next read returns 0 bytes. The lseek function will clear the end-of-file indicator.

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


read 606

S1111 Alsa creat, fread, opeq, write

I * READ . C : T h i s p r o g r a m opens a f i l e named READ . C a n d t r i e s t o r e a d 60 , 000


* byt e s f r om t h a t f i l e u s i ng r e a d . It t h e n d i s p l a y s the a c t u a l
* n umbe r of bytes r e a d f rom READ . C .
*I

#i n c l u d e <fcntl . h> I * N eeded on l y fo r O_RDWR d e f i n i t i on * /


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

c h a r buffe r [ 60000 ] ;

v o i d ma i n ( >
(
i nt f h ;
u n s i g n e d i n t nbytes = 60000 , byt e s r ea d ;

I * Open f i l e f o r i n put : * /
i f ( C f h = open ( " r e a d . c " , O_RDON LY > > -1
==

(
p e r ro r C " open fa i l ed on i n put fi l e " ) ;
exi t C 1 > ;

/ * Rea d i n i nput : * /
i f ( C by t e s read = re a d ( f h , buffe r , nbytes > > <= 0 >
p e r ro r C " P robl em rea d i n g f i l e " ) ;
el se
p r i n t f ( " Re a d % u bytes f rom f i l e \ n " , by t e s r e a d ) ;

c l os e ( f h > :

Output

Re a d 7 4 7 by tes from f i l e
601 realloc Functions

DBBt:l/pllon Reallocate memory blocks.

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

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

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


void _based( void ) *_brealloc( _segment seg, void _based( void ) *memblock,
size_t size );
void _far *_frealloc( void _far *memblock, size_t size );
void _near *_nrealloc( void _near *memblock, size_t size );

memblock Pointer to previously allocated memory block

size New size in bytes


seg Segment selector

Remades The realloc family of functions changes the size of a previously allocated memory block.
The memblock argument points to the beginning of the memory block. If memblock is
NULL, realloc functions in the same way as malloc and allocates a new block of size
bytes. If memblock is not NULL, it should be a pointer returned by calloc, malloc, or a
prior call to realloc.

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, although the new block may be in a
different location.

The memblock argument can also point to a block that has been freed, as long as there has
been no intervening call to the corresponding calloc, malloc, _expand, or realloc func­
tion. If successful, the reallocated block is marked in use.

In large data models (that is, compact-, large-, and huge-model programs), realloc maps to
_frealloc. In small data models (tiny-, small-, and medium-model programs), realloc maps
to _nrealloc.
realloc Functions 608

The various realloc functions reallocate memory in the heap specified in the following list:

Function Heap

realloc Depends on data model of program

_brealloc Based heap specified by seg value

_frealloc Far heap (outside default data segment)

_nrealloc Near heap (inside default data segment)

Retum Value The realloc functions return a void pointer to the reallocated (and possibly moved)
memory block.
The return value is NULL if the size is zero and the buffer argument is not NULL, or if
there is not enough available memory to expand the block to the given size. In the first
case, the original block is freed. In the second, the original block is unchanged.

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.

Campallblllty realloc

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

_brealloc, _frealloc, _nrealloc

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

See Also calloc functions, free functions, malloc functions

I * REALLOC . C : T h i s p ro g r a m a l l o c a t e s a b l o c k of memo ry for buffer


* and then uses _ms i z e t o d i s p l a y the s i z e of that b l oc k . Next , i t
* u s e s r ea l l oc to expa n d t h e amount of memo ry u s ed by buffer
* and t h e n c a l l s _ms i z e a g a i n t o d i s p l a y the n ew amount o f
* memo ry a l l o c a ted t o buffe r .
*I
609 reallac Functions

#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 ( )
(
l on g *buffe r ;
s i z e_t s i ze :

i f ( ( buffe r = ( l on g * ) ma l l oc ( 1 000 * s i zeof ( l on g ) ) ) == N U L L )


exi t ( 1 ) ;

s i z e = _ms i z e ( b u f f e r ) ;
p r i n t f ( " S i z e of b l oc k a ft e r ma l l oc of 1000 l on g s : % u \ n " , s i z e > :

I * Rea l l o c a t e a n d s h ow n ew s i z e : * /
i f ( ( bu f f e r = r ea l l oc C buffe r , s i z e + ( 1 000 * s i zeof ( l on g > > > > == N U L L
exi t ( 1 > :
s i z e = _ms i z e ( b u f f e r > :
p r i n t f ( " S i z e o f b l 9 c k a ft e r rea l l oc of 1 000 more l on g s : % u \ n " , s i z e > :

free ( buffer > :

Output

S i z e of bl o c k a ft e r ma l l oc of 1000 l on g s : 4000
S i z e of b l o c k a ft e r rea l l oc of 1000 more l on g s : 8000
_rectangle Functions 610

DeBt:rlpllan Draw rectangles.

#Include <grapb.h>

short _far _rectangle( short control, short xl, short y1, short x2, short y2 );
short _far _rectangle_w( short control, double wxl, double wyl, double wx2,
double wy2 );
short _far _rectangle_wxy( short control, struct _wxycoord _far *pwxyl,
struct _wxycoord _far *pwxy2 );

control Fill flag

xl , yl Upper-left corner

x2, y2 Lower-right corner

wxl , wyl Upper-left corner

wx2, wy2 Lower-right comer

pwxyl Upper-left corner

pwxy2 Lower-right corner

Remades The _rectangle functions draw a rectangle with the current line style.

The _rectangle function uses the view coordinate system. The view coordinate points
(xl , yl) and (x2, y2) are the diagonally opposed comers of the rectangle.
The _rectangle_w function uses the window coordinate system. The window coordinate
points (wxl, wyl) and (wx2, wy2) are the diagonally opposed corners of the rectangle.

The _rectangle_wxy function uses the window coordinate system. The window coordinate
points (pwxyl) and (pwxy2) are the diagonally opposed corners of the rectangle. The
coordinates for the _rectangle_wxy routine are given in terms of an _wxycoord structure
(defined in GRAPH.ff), which contains the following elements:

Element Description

double wx window x coordinate

double wy window y coordinate


61 1 _rectangle Functions

The control parameter can be one of the following manifest constants:

Constant Action

_ GFILLINTERIOR Fills the figure with the current color using the current fill
mask

_ GBORDER Does not fill the rectangle

If the current fill mask is NULL, no mask is used. Instead, the rectangle is filled with the
current color.

If you try to fill the rectangle with the _floodfill function, the rectangle must be bordered
by a solid line-style pattern.

Retum Value The function returns a nonzero value if the rectangle is drawn successfully, or 0 if not.

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

S11 Also _arc functions, _ellipse functions, _floodfill, _getcolor, _lineto functions,
_pie functions, _setcolor, _setfillmask

&amp� --
--

I * R E CT . C : T h i s p ro g r a m d ra w s a rec t a n g l e . * /

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


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

v o i d ma i n ( )
(
I * F i nd a v a l i d g r a ph i c s mode . * I
i f ( l _s e t v i d eomod e C _MA X RESMO D E )
ex i t ( 1 ) ;

_re c t a n g l e ( _GBORD E R , 80 , 50 , 240 , 1 50 ) ;

getch ( ) ;

_s etv i d eomod e ( _O E FAU LTMOD E ) ;


_registerfonts 612

DBScrlptlan Initializes the fonts graphics system.

#include <graph.h>

short _far _registerfonts( unsigned char _far *pathname );

pathname Path name specifying .FON files to be registered

Remarks The _registerfonts function initializes the fonts graphics system. Font files must be
registered with the _registerfonts function before any other font-related library function
(_getgtextextent, _outgtext, _setfont, _unregisterfonts) can be used.
The _registerfonts function reads the specified files and loads font header information
into memory. Each font header takes up about 140 bytes of memory.

The pathname argument is the path specification and file name of valid .FON files. The
pathname can contain standard DOS wild-card characters.
The font functions affect only the output from the font output function _outgtext; no other
C run-time output functions are affected by font usage.

Return Value The _registerfonts function returns a positive value which indicates the number of fonts
successfully registered. A negative return value indicates failure. The following negative
values may be returned:

Value Meaning

-1 No such file or directory.

-2 One or more of the .FON tiles was not a


valid, binary .FON file.

-3 One or more of the .FON files is damaged.

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

See Also _getfontinfo, _getgtextextent, _outgtext, _setfont, _unregisterfonts

Example See the example for _outgtext.


613 _remapallpalette, _remappalette

Description Remap all palette colors.

#include <graph.h>

short _far _remapallpalette( long _far *colors );


long _far _remappalette( short index, long color );

colors Color value array


index Color index to reassign
color Color value to assign color index to

Remarks The _remapallpalette function remaps the entire color palette simultaneously to the colors
. given in the colors array. The colors array is an array of long integers where the size of the
array varies from 1 6 to 64 to 256, depending on the video mode. The number of colors
mapped depends on the number of colors supported by the current video mode. The
_remapallpalette function works in all video modes (except _ORESCOLOR mode), but
only with EGA, MCGA, or VGA hardware.

The default color v alues for a color text on 16-color graphics mode are shown below:

Number Color Number Color

0 Black 8 Dark gray


1 Blue 9 Light blue
2 Green 10 Light green
3 Cyan 11 Light cyan
4 Red 12 Light red
5 Magenta 13 Light magenta
6 Brown 14 Yellow
7 White 15 Bright white

The first array element specifies the new color value to be associated with color index 0
(the background color in graphics modes). After the call to _remapallpalette, calls to
_setcolor will index into the new array of colors. The mapping done by _remapallpalette
affects the current display immediately.
_remapal/palette, _remappalette 614

The colors array can be larger than the number of colors supported by the current video
mode, but only the first n elements are used, where n is the number of colors supported by
the current video mode, as indicated by the numcolors element of the videoconfig
structure.

The long color value is defined by specifying three bytes of data representing the three
component colors: red, green, and blue.

Each of the three bytes represents the intensity of one of the red, green, or blue component
colors, and must be in the range 0-3 1 . In other words, the low-order six bits of each byte
specify the component's intensity and the high-order two bits should be zero. The fourth
(high-order) byte in the long is unused and should be set to zero. The diagram below
shows the ordering of bytes within the long value.

For example, to create a lighter shade of blue, start with lots of blue, add some green, and
maybe a little bit of red. The three-byte color value would be:

bl u e byte g reen byt e r e d byte


000 1 1 1 1 1 001 0 1 1 1 1 000 1 1 1 1 1
hi gh ------ > l ow o r d e r

Manifest constants are defined i n GRAPH.H for the default color values corresponding to
color indices 0-15 in color text modes and 1 6-color graphics modes, as shown below:

Index Constant Index Constant

0 _BLACK 8 GRAY
_

1 _BLUE 9 _LIGHTBLUE
2 _GREEN 10 LIGHTGREEN
_

3 _CYAN 11 LIGHTCYAN
_

4 _RED 12 LIGHTRED
_

5 _MAGENTA 13 _LIGHTMAGENTA
6 _ BROWN 14 _YELLOW
7 _WHffE 15 _BRIGHTWIUTE

The VGA supports a palette of 262, 1 44 colors (256K) in color modes, and the EGA sup­
ports a palette of only 64 different colors. Color values for EGA are specified in exactly
the same way as with the VGA; however, the low-order four bits of each byte are simply
ignored.

The _remappalette function assigns a new color value color to the color index given by
index. This remapping affects the current display immediately.
615 _remapallpalette, _remappalette

The _remappalette function works in all graphics modes, but only with EGA, MCGA,
or VGA hardware. An error results if the function is called while using any other
configuration.
The color value used in _remappalette is defined and used exactly as noted above for
_remapallpalette. The range of color indices used with _remappalette depends on the
number of colors supported by the video mode.

The _remapallpalette and _remappalette functions do not affect the presentation­


graphics palettes, which are manipulated with the _pg_getpalette, _pg_setpalette, and
_pg_resetpalette functions.
If a VGA or MCGA adapter is connected to an analog monochrome monitor, the color
value is transformed into its gray-scale equivalent, based on the weighted sum of its red,
green, and blue components (30% red + 50% green + 1 1 % blue). The original red, green,
and blue values are lost.

Return Value If successful, _remapallpalette returns -1 (short). In case of an error, _remapallpalette


returns 0 (short).

If successful, _remappalette returns the color value previously assigned to index, or -1 if


the function is inoperative (not EGA, VGA, or MCGA), or if the color index is out of
range.
Note that _remapallpalette returns a short value and _remappalette returns a long value.

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

See Also _selectpalette, _setbkcolor, _setvideomode

I * RM P A L P A L . C : T h i s exampl e i l l u s t ra t e s f u n c t i on s fo r a s s i g n i ng
* c o l o r v a l u e s t o c o l o r i n d i c e s . Fun c t i o n s i l l u s t ra t ed i n c l ude :
* _rema ppa l ette _rema pa l l pa l ette
*I

#i n c l ude <graph . h>


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

#def i n e RGB C r , g , b ) ( ( ( l on g ) ( ( b ) < < 8 I C g ) ) < < 8 > I C r ) )


I * M a c ro f o r mi x i n g Red , Green , a n d B l u e e l eme n t s of c o l o r */
_remapallpalette _remappalette , 616

l on g tmp , p a l [ 2 5 6 ] ;
v o i d ma i n ( )
{
s h o rt red , b l u e , g reen ;
s ho r t i n c , i , mod e , c e l l s , x , y , x i n c , y i n c ;
char buf[40] ;
s t ruct v i deocon f i g vc ;

I * M a k e s u r e a l l p a l ette numb e r s a re v a l i d . * /
f o r ( i = 0 ; i < 2 5 6 ; i ++ >
pa l [ i ] = _B LAC K ;

I * Loop t h r o u g h ea c h g r a p h i c s mode t h a t s upports pa l ettes . * /


fo r ( mode _M RES4CO L O R ; mode < = _M R E S2 5 6 C O LO R ; mod e++ )
{
=

i f ( mod e = _ERESNOCOLOR
mod e++ ;
i f ( ! _s e t v i d e omod e C mod e
cont i nue ;

I * Set v a r i a bl e s fo r ea c h mod e . */
_g e t v i d e o c o n f i g C & v c ) ;
s w i t c h ( v c . n umc o l o r s >
{
c a s e 256 : / * Ac t i v e b i t s i n t h i s o r d e r : */
cel l s = 13 ;
i nc = 1 2 ; / * ? ? ? ? ? ? ? ? ? ? bbbbbb ? ? gg g g g g ? ? r r r r r r * /
brea k ;
case 16:

i f ( e v e . mode = _E RESCO LO R ) 1 1 e v e . mode = _V R E S 1 6 C O LO R ) )


cel l s = 4 ;

i nc = 1 6 ; / * ? ? ? ? ? ? ? ? ? ?bb? ? ? ? ? ?gg? ? ? ? ? ? r r? ? ? ? * /
el se
i nc = 32 : I * ? ? ? ? ? ? ? ? ? ? Bb ? ? ? ? ? ? Gg? ? ? ? ? ? R r ? ? ? ? * /
b r ea k ;
case 4:
cel l s = 2;
i nc = 32 ; I * ? ? ? ? ? ? ? ? ? ? Bb ? ? ? ? ? ? Gg ? ? ? ? ? ? R r ? ? ? ? * /
brea k ;
defa u l t :
conti nue :

x i n c = v c . n umxp i x e l s I c e l l s ;
y i n c = v c . numy p i x e l s I c e l l s ;
611 _remapallpalette, _remappalette

I * F i l l pa l ette a r r a y s i n BGR o r d e r . * /
fo r e i = 0 , b l ue = 0 ; b l ue < 64 ; b l ue + = i n c >
fo r ( g r een = 0 ; g r een < 64 ; g r een += i n c )
fo r ( red 0 ; red < 64 ; red += i n c )
(
-

pa l [ i ] = RGB C red , g r een , bl u e ) ;


I * Spec i a l c a s e of u s i n g 6 b i t s t o r e p r e s e n t 1 6 col o r s .
* I f b o t h b i t s a re on f o r a ny c o l o r , i n t en s i ty i s s et .
* I f o n e b i t i s s et f o r a c o l o r , t h e c o l o r i s on .
*I

p a l [ i + S J = pa l [ i J I C pa l [ i J > > 1 ) ;
i f ( i nc = 32 )

i ++ ;

I * I f pa l e t t e s a v a i l a b l e , rema p a l l pa l e t t e s a t on c e . * I
i f ( ! _r ema pa l l pa l et t e C p a l > >
(
_s et v i d eomod e ( _D E FAU LTM O D E ) ;
_o u t t ex t ( " P a l e t t e s not a v a i l a b l e w i t h t h i s a d a p t e r • ) ;
ex i t ( 1 ) ;

I * D r a w c o l o red s q u a res . * /
fo r e i =0, x 0 ; x < C x i n c * c e l l s ) ; x += x i n c
=

fo r ( y = 0 ; y < C y i n c * c e l l s ) ; y + = y i n c )
(
_s e t c o l o r ( i ++ ) ;
_rec t a n g l e ( _G F I L L I NT E R I O R , x , y , x + x i n c , y + y i n c ) ;

I * N o t e t h a t for 2 5 6 - c o l o r mod e , not a l l c o l o r s a re s h own . T h e number


* of c o l o r s from m i x i n g t h ree ba s e c o l o r s can never b e t h e s a me a s
* t h e n umber t h a t c a n b e s h own o n a two - d i men s i o n a l g r i d .
*I
s p r i n t f ( · bu f , " Mode %d h a s %d c o l o r s • , v c . mode , v c . n umc o l o r s > :
_s etc o l o r < vc . n umc o l o r s I 2 ) ;
_o uttext ( buf ) ;
getc h C l ;
_remapallpalette _remappalette , 618

I * C h a n g e ea c h p a l ette e n t ry s ep a r a t e l y i n GRB o r d e r . * I
fo r ( i = 0 , g reen 0 ; g reen < 64 ; g reen += i n c )
=

for ( red a 0 ; red < 64 ; red +- i n c )


for C bl ue =0 ; bl u e < 64 ; b l u e +- i nc
{
tmp = RGB C red , g reen , b l u e ) ;
_rema pp a l ette ( i , tmp ) ;

_rema ppa l e t t e ( i + 8 , tmp I C tmp > > 1 ) ) ;


i f ( i nc 32 )
==

i ++ ;
)
getch ( ) ;
)
_s et v i d eomode ( _D E FAU LTMOD E ) ;
619 remove

Description Deletes a file.

#include <Stdio.h> Required for ANSI compatibility


#include <io.h> Use either IO.H or STDIO.H

int remove( const char *path );

path Path name of file to be removed

Remarks The remove function deletes the file specified by path.

Return Value The function returns 0 if the file is successfully deleted. Otherwise, it returns -1 and sets
errno to one of these values:

Value Meaning

EACCES Path name specifies a read-only file.


ENOENT File or path name not found, or path name specifies a
directory.

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

See Also unlink

I * R E M O V E . C : T h i s p r o g r a m u s e s remove to d e l ete REMO V E . O BJ . * /

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

v o i d ma i n ( )
(
i f ( remo v e ( " remo v e . obj " ) == -1 )
p e r r o r ( " C o u l d not d e l ete ' R EMOV E . O BJ ' " ) ;
el s e
p r i n t f ( " De l eted ' R EMO V E . OBJ ' \ n " ) ;

Output

Del e t e d ' R EMO V E . O BJ '


rename 620

Description Renames a file or directory.

#include <Stdio.h> Required for ANSI compatibility


#include <io.h> Use either IO.H or STDIO.ff

int rename( const char *oldname, const char *newname );

oldname Pointer to old name


newname Pointer to new name

Remarks The rename function renames the file or directory specified by o/dname to the name given
by newname. The old name must be the path name of an existing file or directory. The new
name must not be the name of an existing file or directory.

The rename function can be used to move a file from one directory to another by giving a
different path name in the newname argument. However, files cannot be moved from one
device to another (for example, from drive A to drive B). Directories can only be renamed,
not moved.

Return Value The rename function returns 0 if it is successful. On an error, it returns a nonzero value
and sets errno to one of the following values:

Value Meaning

EACCES File or directory specified by newname already exists or could


not be created (invalid path); or oldname is a directory and
newname specifies a different path.
ENOENT File or path name specified by oldname not found.
EXDEV Attempt to move a file to a different device.

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

I * R E N AM E R . C : T h i s p ro g r a m a t t empt s to rename a fi l e n a med RENAM E R . OBJ t o


* R E N AM E R . J BO . F o r t h i s ope ra t i o n t o s u c c e e d , a f i l e n a med R E N AM E R . O BJ
* m u s t e x i s t a n d a f i l e n amed R E N AM E R . J BO m u s t not e x i s t .
*/

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


621 rename

v o i d ma i n ( )
(
i nt resul t ;
c h a r ol d [ ] = " R ENAM E R . OBJ " , new [ ] " RE NAM E R . J BO " ;

I * Attempt t o rename f i l e : * /
r e s u l t = ren a me ( o l d , new ) ;
i f ( res u l t ! = 0 )
p r i n t f ( " C o u l d not r e n a me ' % s ' \ n " , o l d ) ;
el se
p r i n t f ( " F i l e ' %s ' r e n a med t o ' %s ' \ n " , o l d , n ew ) ;

Output

F i l e ' R ENAM E R . OBJ ' renamed t o ' RE N AM E R . J BO '


rewind 622

Description Repositions the file pointer to the beginning of a file.

#include <Stdio.h>

void rewind( FILE *stream ) ;

stream Pointer to FILE structure

Remarks The rewind function repositions the file pointer associated with stream to the beginning of
the file. A call to rewind is equivalent to

(void) fseek( stream, OL, SEEK_SET ) ;


except that rewind clears the error indicators for the stream, and fseek does not. Both
rewind and fseek clear the end-of-file indicator. Also, fseek returns a value that indicates
whether the pointer was successfully moved, but rewind does not return any value.
You can also use the rewind function to clear the keyboard buffer. Use the rewind func­
tion with the stream stdio, which is associated with the keyboard by default.

Return Value The rewind function has no return value.

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

I * R EW I N D . C : T h i s p ro g r a m f i r s t open s a f i l e n a med R E W I N D . OUT f o r i n put a nd


* o u t p u t a n d w r i t e s two i n t e g e r s t o t h e f i l e . Next , i t u s e s rewi nd t o
* repo s i t i o n t h e f i l e p o i n t e r t o t h e be g i n n i n g of t h e f i l e a n d r e a d s
* t h e d a t a ba c k i n .
*I

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

v o i d ma i n ( )
{
FI LE * s t ream ;
i nt d a ta l , data 2 ;

data l 1;=

data2 = -37 ;

i f ( ( s t re a m = fopen C " r ewi n d . o ut • , " w+ " ) ) ! = N U L L )


{
f p r i n t f ( s t r e a m , " %d %d " , d a t a l , d a t a 2 ) ;
p r i n t f ( " T h e v a l u e s w r i t t e n a re : %d a nd % d \ n " , d a t a l , d a t a 2 ) ;
rewi n d ( s t r e a m ) ;
f s c a n f C s t r e a m , " Sd Sd " , &d a t a l , & d a t a 2 - ) ;
p r i n t f C " Th e v a l u e s r e a d a r e : Sd a n d S d \ n " , d a t a l , d a t a 2 ) ;
fcl oseC st ream > ;

T h e v a l u e s w r i t t e n a re : 1 a n d - 3 7
T h e v a l ues r e a d a re : 1 a n d - 3 7
rmdir 624

Description Deletes a directory.

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

int rmdir( char *dirname );

dirname Path name of directory to be removed

Remades The rmdir function deletes the directory specified by dirname. The directory must be
empty, and it must not be the current working directory or the root directory.

Retum Value The rmdir function returns the value 0 if the directory is successfully deleted. A return
value of -1 indicates an error, and errno is set to one of the following values:

Value Meaning

EACCES The given path name is not a directory; or the directory is not
empty; or the directory is the current working directory or the
root directory.
ENOENT Path name not found.

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

See Also chdir, mkdir

Exampm ��������-

1 * MAKE D I R . C * /
#i n c l u d e < d i r e ct . h>
#i ncl ude <stdl i b . h>
#i n c l u d e < s t d i o . h >

v o i d ma i n { )
[
i nt r e s u l t ;
625 rmdir

i f ( mkd i r C " \ \ t e s t tmp • > == 0 >


{
p r i n t f ( " D i rec t o ry ' \ \ t e s t tmp ' wa s s uc c e s s fu l l y c re a t ed \ n " ) ;
s y s t em ( " d i r \ \ t es t tmp • ) ;
i f ( rmd i r ( " \ \ t e s ttmp • > == 0 >
p r i n t f C " D i r e c t o ry ' \ \ t e s ttmp ' wa s s u c c e s s f u l l y removed \ n " );
el se
p r i n t f ( " P robl em remov i n g d i r e c t o ry ' \ \ t es t tmp ' \ n " ) ;
)
el se
p r i n t f ( " P robl em c rea t i ng d i rec t o ry ' \ \ t e s t tmp ' \ n " ) ;

Output

D i r e c t o ry ' \ t e s t tmp ' wa s s u c c e s s f u l l y c re a t e d

T h e v o l ume l a bel i n d r i v e C i s 052 .


D i r e c t o ry of C : \ T ESTTM P

< D I R> 6 - 1 9 -89 1 1 : 20 a


< D I R> 6 - 1 9 -89 1 1 : 20a
2 Fi l e ( s ) 1 2730368 bytes f r e e
D i r e c t o ry ' \ t e s ttmp ' wa s s u c c e s s fu l l y removed
rmtmp 626

OeBt:r/ptian Removes temporary files.

#include <Stdio.h>

int rmtmp( void );

Remarks The rmtmp function is used to clean up all the temporary files in the current directory.
The function removes only those files created by tmpfile and should be used only in the
same directory in which the temporary files were created.

Return Value The rmtmp function returns the number of temporary files closed and deleted.

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

See Also flushall, tmpftle, tmpnam

I * TM P F I L E . C : T h i s p ro g r a m u s e s tmpfi l e to c r e a t e a t emp o r a ry f i l e ,
* t h en d e l e t e s t h i s f i l e wi t h rmtmp .
*I

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

v o i d ma i n ( )
(
F I LE *st ream ;
c h a r t emp s t r i ng [ ] = " St r i n g t o be w r i t t en " ;
i nt i ;

/ * C re a t e t empo r a ry f i l es . * /
for e i = l ; i <= 1 0 ; i ++ )
(
i f ( ( s t ream = tmpfi l e ( ) ) == N U L L
p e r r o r C " C o u l d n o t open n e w t emp o r a ry f i l e \ n " ) ;
el se
p r i n t f C " Temp o r a ry f i l e %d w a s c re a t ed \ n " , i ) ;

I * Remov e t empo r a ry f i l es . * /
p r i n t f ( " %d t emp o r a ry f i l es d e l eted \ n " , rmtmp ( ) ) ;
627 rmtmp

Output

Temporary fi 1 e 1 was created


Temporary f i le 2 was created
Temporary fi 1 e 3 was created
Temporary fi 1 e 4 was created
Temporary f i le 5 was created
Temporary fi 1 e 6 was created
Temporary fi 1 e 7 was created
Temporary f i le 8 was created
Temporary f i le 9 was created
Temporary f i le 10 was created
10 temporary f i l es deleted
_ ro� rou _ �s

Description Rotate bits to the left (_rotl) or right (_rotr).

#include <Stdlib.h>

u�igned int _rotl( unsigned int value, int shift );


unsigned int _rotr( unsigned int value, int shift );

value Value to be rotated


shift Number of bits to shift

Remades The _rotl and _rotr functions rotate the unsigned value by shift bits. The _rotl function
rotates the value left. The _rotr function rotates the value right. Both functions "wrap" bits
rotated off one end of value to the other end.

Return Value Both functions return the rotated value. There is no error return.

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

See Also _Irotl, _lrotr

I * ROT . C : T h i s p r o g r a m u s e s _rot r a n d _rot l w i t h d i f f e r e n t s h i ft


* v a l ues to rotate an i ntege r .
*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 >

v o i d ma i n ( )
{
u n s i gned v a l = 0x0fd 9 3 ;

pri ntf( " 0x%4 . 4x r o t a t e d l e ft t h r e e t i m e s i s 0 x % 4 . 4 x \ n " ,


v a l , _rot l ( v a l , 3 ) >:
p r i n t f ( " 0x%4 . 4x r o t a t e d r i g h t f o u r t i me s i s 0 x % 4 . 4 x \ n " ,
v a 1 , _ r o t r ( v a.l , 4 > );
629 _roll _rotr
,

Output

0xfd93 rota t ed l eft t h ree t i me s i s 0xec9f


0xfd93 rota t ed r i g h t f o u r t i me s i s 0x3fd9
scant 630

Description Reads formatted data from the standard input stream.

#include <Stdio.h>

int scant( const char *format [,argumentD ... ) ;

format Format control

argument Optional argument

Remarks The scanf function reads data from the standard input stream stdio into the locations given
by argument. Each argument must be a pointer to a variable with a type that corresponds
to a type specifier in format. The format controls the interpretation of the input fields. The
format can contain one or more of the following:

• White-space characters: blank (' '); tab (\t); or newline (\n). A white-space character
causes scanf to read, but not store, all consecutive white-space characters in the input
up to the next non-white-space character. One white-space character in the format
matches any number (including 0) and combination of white-space characters in the
input.
• Non-white-space characters, except for the percent sign ( % ). A non-white-space char­
acter causes scanf to read, but not store, a matching non-white-space character. If the
next character in stdio does not match, scanf terminates.

• Format specifications, introduced by the percent sign (%). A format specification


causes scanf to read and convert characters in the input into values of a specified type.
The value is assigned to an argument in the argument list.

The format is read from left to right. Characters outside format specifications are expected
to match the sequence of characters in stdio; the matching characters in stdio are scanned
but not stored. If a character in stdio conflicts with the format specification, scanf termi­
nates. The character is left in stdio as if it had not been read.
When the first format specification is encountered, the value of the first input field is con­
verted according to this specification and stored in the location that is specified by the first
argument. The second format specification causes the second input field to be converted
and stored in the second argument, and so on through the end of the format string.
An input field is defined as all characters up to the first white-space character (space, tab,
or newline), or up to the first character that cannot be converted according to the format
specification, or until the field width (if specified) is reached. If there are too many argu­
ments for the given specifications, the extra arguments are evaluated but ignored. The re­
sults are unpredictable if there are not enough arguments for the format specification.
681 scant

A fonnat specification has the following fonn:


% [*D [widthD [ { F I N } D [ { h I l } Dtype
Each field of the fonnat specification is a single character or a number signifying a particu­
lar fonnat option. The type character, which appears after the last optional fonnat field, de­
termines whetherthe input field is interpreted as a character, a string, or a number. The
simplest fonnat specification contains only the percent sign and a type character (for ex­
ample, % s ) .

Each field of the fonnat specification is discussed in detail below. If a percent sign ( % ) is
followed by a character that has no meaning as a fonnat-control character, that character
and the following characters (up to the next percent sign) are treated as an ordinary
sequence of characters--that is, a sequence of characters that must match the input. For ex­
ample, to specify that a percent-sign character is to be input, use %% •

An asterisk (*) following the percent sign suppresses assignment of the next input field,
which is interpreted as a field of the specified type. The field is scanned but not stored.
The width is a positive decimal integer controlling the maximum number of characters to
be read from stdin. No more than width characters are converted and stored at the corre­
sponding argument. Fewer than width characters may be read if a white-space character
(space, tab, or newline) or a character that cannot be converted according to the given for­
mat occurs before width is reached.
The optional F and N prefi�es allow the user to specify whether the argument is far or
near, respectively. F should be prefixed to an argument pointing to a far object, while N
should be prefixed to an argument pointing to a near object. Note also that the F and N pre­
fixes are not part of the ANSI definition for scanf, but are instead Microsoft extensions,
which should not be used when ANSI portability is desired.
The optional prefix I indicates that the long version of the following type is to be used,
while the prefix h indicates that the short version is to be used. The corresponding
argume111 should point to a long or double object (with the I character) or a short object
(with the h character). The I and h modifiers can be used with the d, i, n, o, x, and u type
characters. The I modifier can also be used with the e, f, and g type characters. The I and h
modifiers are ignored if specified for any other type.
For scanf, N and F refer to the "distance" to the object being read in (near or far) and h
and I refer to the "size" of the object being read in ( 16-bit short or 32-bit long). The list
below clarifies this use of N, F, I, and h:
scant 632

Program Code Action

scanf( " % N s " , &x ) ; Read a string into near memory


scanf( " % F s " , &x ) ; Read a string into far memory
scanf( " % Nd " , & x ) ; Read an int into near memory
scanf( " % Fd " , &x ) ; Read an int into far memory
scanf( " % N l d " , &x ) ; Read a long int into near memory
scanf( " % F l d " , &x ) ; Read a long int into far memory
scanf( " % N h p " , &x ) ; Read a 1 6-bit pointer into near memory
scanf( " % N l p " , & x ) ; Read a 32-bit pointer into near memory
scanf( " % F h p " , &x ) ; Read a 1 6-bit pointer into far memory
scanf( " % F l p " , &x ) ; Read a 32-bit pointer into far memory

The type characters and their meanings are described in Table R.5.
To read strings not delimited by space characters, a set of characters in brackets ([ ]) can
be substituted for the s (string) type character. The corresponding input field is read up to
the first character that does not appear in the bracketed character set. If the first character
in the set is a caret ( " ), the effect is reversed: the input field is read up to the first character
that does appear in the rest of the character set.
Note that % [a·z] and % [z·a] are interpreted as equivalent to % [abcde...z]. This is a com­
mon scanf extension, but note that it is not required by the ANSI specification.
To store a string without storing a terminating null character ('\0'), use the specification
% nc, where n is a decimal integer. In this case, the c type character indicates that the argu- .
ment is a pointer to a character array. The next n characters are read from the input stream
into the specified location, and no null character ('\O') is appended. If n is not specified, the
default value for it is 1 .

The scanf function scans each input field, character by character. It may stop reading a par­
ticular input field before it reaches a space character for a variety of reasons: the specified
width has been reached; the next character cannot be converted as specified; the next char­
acter conflicts with a character in the control string that it is supposed to match; or the next
character fails to appear in a given character set. For whatever reason, when scanf stops
reading an input field, the next input field is considered to begin at the first unread charac­
ter. The conflicting character, if there is one, is considered unread and is the first character
of the next input field or the first character in subsequent read operations on stdio.
scant

Table R.5 Type Characters for scanf

Character Type of lnput Expected Type of Argument

d Decimal integer Pointer to int


0 Octal integer Pointer to int
1
x Hexadecimal integer Pointer to int
Decimal, hexadecimal, or octal in­ Pointer to int
teger
u Unsigned decimal integer Pointer to unsigned int
u Unsigned decimal integer Pointer to unsigned long
e, E Floating-point value consisting of Pointer to float
f an optional sign (+ or -), a series of
g, G one or more decimal digits contain­
ing a decimal point, and an optional
exponent ("e" or "E") followed by
an optionally signed integer value.

c Character. White-space characters Pointer to char


that are ordinarily skipped are read
when c is specified; to read the next
non-white-space character, use % l s .
s String Pointer to character array large
enough for input field plus a termi­
nating null character ('\0'), which is
automatically appended.
n No input read from stream or buffer. Pointer to int, into which is stored
the number of characters success­
fully read from the stream or buffer
up to that point in the current call to
scanf.
p Value in the form xx:xx:yyyy, where Pointer to far pointer to void
the digits x and y are uppercase hex­
adecimal djgits.

t Since the input for a %x fonnat specifier is always interpreted as a hexadecimal number, the input should
not include a leading Ox. (If Ox is included, the 0 is interpreted as a hexadecimal input value.)

Return Value The scanf function returns the number of fields that were successfully converted and as­
signed. The return value may be less than the number requested in the call to scanf. The re­
turn value does not include fields that were read but not assigned.
The return value is EOF if the end-of-file or end-of-string is encountered in the first at­
tempt to read a character.
scant 634

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

S1111 A/sa fscanf, printf, sscanf, vfprintf, vprintf, vsprintf

I * SCAN F . C : T h i s p r o g r a m r e c e i v e s f o rma t t ed i n p u t u s i n g s c a n f .
#i n c l ude < s t d i o . h>
*/

v o i d ma i n ( )
(
i nt i ;
fl oat fp ;
char c , s [81] ;
i nt resul t ;

printfC " E n t e r a n i n t e g e r , a f l o a t i n g - p o i n t n umbe r , •


• a cha racter and a stri ng : \n" > ;
r e s u l t m s c a n f C " Sd S f Sc S s " , & i , & f p , &c , s ) ;

pri ntf C " \ nT h e n um b e r o f f i e l d s i n p u t i s Sd \ n " , r e s u l t ) ;


pri ntf C " T h e c o n t e n t s a re : S d S f S c S s \ n " , i , fp , c , s > ;

Output

E n t e r a n i n t e g e r , a f l o a t i n g - p o i n t n umb e r , a c h a ra c t e r a n d a s t r i n g :
71
98 . 6
h
Whi te space stops i nput

T h e n um b e r o f f i e l d s i n p u t i s 4
The contents a r e : 7 1 98 . 599998 h Wh i te
635 _scralltextwindow

Description Scrolls the text in a text window.

#include <graph.h>

void _far _scrolltextwindow( short lines );

lines Number of lines to scroll

Remarks The _scrolltextwindow function scrolls the text in a text window (previously defined by
the _settextwindow function). The lines argument specifies the number of lines to scroll.
A positive value of lines scrolls the window up (the usual direction); a negative value
scrolls the window down. Specifying a number larger than the height of the current text
window is equivalent to calling _clearscreen( _GWINDOW ) . A value of 0 for lines has no
effect on the text.

Return Value None.

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

See Also _gettextposition, _outmem, _outtext, _settextposition, _settextwindow

Example __________________________________________________________________�

/ * S C RT X W I N . C : T h i s p r o g r a m d i s p l a y s text i n text w i ndows a n d t h en


* s c r o l l s , i n s e r t s , a n d d e l etes l i n es .
*I

#i n c l u d e < s t d i o . h >
#i n c l u d e < c on i o . h >
#i n c l u d e < g r a p h . h >

voi d del etel i ne C voi d > :


voi d i nsertl i ne C voi d > :
v o i d s t a t u s ( c h a r *ms g ) ;

v o i d ma i n ( )
{
s h o r t r ow ;
c h a r b u f [ 40 J ;

I * Set up s c reen for s c ro l l i n g , a n d put t ex t w i n d ow a ro u n d s c ro l l a rea . * /


_s ettext rows ( 2 5 ) ;
_c l ea r s c reen ( _GC LEARSC R E E N ) ;
_scrolltextwindow 636

fo r ( r ow = 1 ; row <= 2 5 ; row++


(
_s ettextpos i t i on ( r ow , 1 ) ;
s p r i n t f ( buf , " L i n e %c %2 d " , row + ' A ' - 1 ,. r ow ) ;
_o uttext C buf ) ;
I
getch ( ) ;
_s ettextw i n d ow C 1 , 1 , 2 5 , 1 0 ) ;

I * D e l ete s ome l i n e s . * /
_s ettextpos i t i on C 1 1 , 1 ) ;
fo r ( row = 1 2 ; row < 20 ; row++
del etel i ne ( ) ;
s t a t u s ( " D e l eted 8 l i n e s " ) ;

/ * I n s e rt s ome l i n e s . * /
_s e t t e x t po s i t i on ( 5 , 1 ) ;
for e row = 1 ; row < 6 ; row++
i n s e rt l i n e ( ) ;
s t a t u s < " I n s e rted 5 l i n es " ) ;

I * S c r o l l u p a nd d own . * /
_s c r o l l t ex tw i n d ow C 7 ) ;
-

s t a t u s ( " S c r o l l ed d own 7 l i n e s • ) ;
_s c r o l l t e x tw i n d ow C 5 ) ;
s t a t u s ( " Sc rol l ed u p 5 l i n e s • ) ;
_s etv i d eomod e ( _D E FAU LTMO D E ) ;

I * Del e t e l i n e s by s c r o l l i n g t h em off t h e top of t h e c u r r ent text w i ndow .


* S a v e a n d r e s t o r e o r i g i n a l w i n d ow .
*I
v o i d del e t e l i n e ( )
{
s h o r t l eft , top , r i g h t , bottom ;
s t r u c t r c c o o rd r e ;

_get textw i n d ow C &top , & l eft , &bottom , & r i g h t ) ;


r e = _g ettextpo s i t i o n C l ;
�s ettextw i n d ow ( r e . row , l eft , b o t t om , r i g h t ) ;
_s c r o l l textw i n d ow ( _GSC RO L LU P ) ;
_s ettextw i ndowC top , l e ft , bottom , r i g h t ) ;
_s ettextpo s i t i on C r e . r ow , r e . c o l ) ;
631 _sc_rolltextwindow

I * I n s e rt s ome l i n es by s c ro l l i n g i n b l a n k l i n e s from t h e t o p of t h e
* c u r rent t e x t w i ndow . S a v e a n d r e s t o r e o r i g i n a l wi n d ow .
*I
voi d i nsertl i ne ( )
I
s h o r t l e ft , t o p , r i g h t , bottom :
s t r u c t r c c o o rd re :

_g ettextw i ndow ( &top , & l eft , &bottom , & r i g h t > :


r e = _g ettextpo s i t i on < > :
_s ettextw i n d ow ( re . r ow , l e ft , bottom , r i g h t > :
_s c ro l l textw i n d ow ( _GS C R O L LDOWN > :
_s ettextw i n d ow ( top , l e ft , bottom , r i g h t > :
_s ettextpo s i t i on ( r e . r ow , re . c o l > :

I * D i s p l ay a nd c l ea r s t a t u s i n i t s own wi ndow . * /
v o i d s t a t u s ( c h a r *ms g )
I
s h o r t l eft , top , r i g h t , bottom :
s t r u c t r c c o o rd re :

_g ettextw i n d ow C &top , & l eft , &bottom , & r i g h t > :


_s ettextw i n d ow ( 1 , 50 , 2 , 80 l :
_ou t t ex t ( m s g l :
getc h C l :
_c l ea r s c reen ( _GW I N DOW l :
_s ettextw i n d ow C top , l e ft , bottom , r i g h t l :
_searchenv BSB

Daer/pt/an Searches for a file using environment paths.

#include <Stdlib.h>

void searchenv( char *filename, char *varname, char *pathname );

filename Name of file to search for


varname Environment to search

pathname Buffer to store complete path

Remam The _searchenv routine searches for the target file in the specified domain. The varname
variable can be any environment variable which specifies a list of directory paths, such as
PATH, LIB, INCLUDE, or other user-defined variables. It is most often PATH, which
searches forfilename on all paths specified in the PATH variable. The _searchenv func­
tion is case-sensitive, so the varname variable should match the case of the environment
variable.

The routine first searches for the file in the current working directory. If it doesn't find the
file, it next looks through the directories specified by the environment variable.
If the target file is found in one of the directories, the newly created path is copied into the
buffer pointed to by pathname. You must ensure that there is sufficient space for the con­
structed path name. If the filename file is not found, pathname will contain an empty null­
terminated string.

Return Value The _searchenv function does not return a v alue.

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

See Also getenv, putenv

Exampm --------�

I * S EA RC H E N . C : T h i s p ro g r a m s e a r c h e s for a f i l e i n a d i r e c t o ry
* s p ec i f i ed by a n e n v i ronment v a r i a b l e .
*I

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


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

v o i d ma i n ( )
(
c h a r p a t h bu f f e r [_MAX_PATH ] ;
c h a r sea rchfi l e[ ] = • c l . EXE• ;
c h a r e n v v a r [ ] - • PATH • ;
I * Sea r c h f o r f i l e i n PATH en v i ronment v a r i a b l e : * /
_s ea rc h en v C s e a rc h f i l e , e n v v a r , p a t hbuffer ) ;
i f ( *pa t h bu f f e r ! - \ 0 )
' '

p ri nt f ( • Pa t h f o r S s : Ss \ n • , s e a r c h f i l e , p a t hbuffer ) ;
el se
p r i n t f C " S s n o t fou n d \ n " , s e a r c h f i l e ) ;

Output

P a t h fo r C L . EX E : C : \ B I N \ C L . E X E
segread 640

Daer/pl/on Gets the current v alues of segment registers.

#include <dos.h>

void segread( struct SREGS *segregs );

segregs Segment-register values

Remarks The segread function fills the structure pointed to by segregs with the current contents of
the segment registers. The SREGS union is described in the reference section for int86x.
This function is intended to be used with the intdosx and int86x functions to retrieve
segment-register values for later use.

Return Value None.

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

See Also FP_SEG, intdosx, int86x

I * S E G READ . C : T h i s p r o g r a m g e t s t h e c u r re n t s egment v a l u e s wi t h s eg r ea d . * /

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


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

v o i d ma i n ( )
[
s t ruct S R E G S s e g r eg s ;
u n s i g n e d c s , ds , e s , s s ;

I * Rea d t h e s egment reg i s t e r v a l u e s * /


s eg r ea d ( & s e g re g s ) ;
c s = s eg re g s . c s ;
d s = s eg r e g s . d s ;
e s = s eg r e g s . es ;
s s = s eg r e g s . s s ;
p r i n t f ( • c s = 0x% . 4x OS = 0x% . 4x ES = 0x% . 4x SS = 0x% . 4x \ n " ,
CS , d s , es , S S ) ;
641 segread

Output

CS = 0x0047 OS = 0x0067 ES = 0x0067 SS = 0x0067

CS = 0x2bcc OS = 0x2ce8 ES = 0x2ba 3 SS = 0x2ce8


_selectpalette

Daar/pllon Selects a graphics palette.

#include <graph.h>

short _far _selectpalette( short number );

number Palette number

R1matb The _selectpalette function works only under the video modes _MRES4COLOR and
_MRESNOCOLOR. A palette consists of a selectable background color (Color 0) and three
set colors. Under the _MRES4COLOR mode, the number argument selects one of the four
·

predefined palettes shown in Table R.6.

Table R.6 _MRES4COLOR Palette Colors

Color Index

Palette Number Color l Color 2 Color3

0 Green Red Brown


Cyan Magenta Light
gray
2 Light green Light red Yellow
3 Light cyan Light magenta White

The _MRESNOCOLOR video mode is used with black-and-white displays, producing


palettes consisting of various shades of gray. It will also produce color when used with a
color display. The number of palettes available depends upon whether a CGA or EGA
hardware package is employed. Under a CGA configuration, only the two palettes shown
in Table R.7 are available.

Table R.7 _MRESNOCOLOR Mode CGA Palette Colors

Color Index

Palette Number Color l Color 2 Color3

0 Blue Red Light


gray
Light blue Light red White
643 _selectpalette

Under the EGA configuration, the three palettes shown in Table R.8 are available in the
_MRESNOCOLOR video mode.

Table R.8 MRESNOCOLOR Mode EGA Palette Colors


_

Color Index

Palette Number Color I Color 2 Color3

0 Green Red Brown


1 Light green Light red Yellow
2 Light cyan Light red Yellow

Note that with an EGA in MRESNOCOLOR video mode, Palette 3 is identical to


- ·

Palette 1 .

R1tum Value The function returns the value of the previous palette. There is no error return.

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

See Also _getvideoconfig, _setbkcolor, _setvideomode

I * S E LPAL . C : T h i s p r o g r a m c h a n g e s t h e c u rrent CGA p a l ette . * /

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


#i n c l u d e <stdl i b . h>
#i n c l u d e <coni o . h>
#i n c l u d e <graph . h>

l on g b k c o l o r [ 8 ] { _B LAC K , _B LU E , _G RE E N , _CYAN ,
_WH I T E } ;
=

_R E D , _MA G ENTA , _B ROW N ,


c h a r * b k n a me [ ] = { " B LAC K " , " B LU E " , " G R E EN " , " CYAN " ,
" RE D " , " MAGENTA " , " B ROWN " , " WH I T E " l ;
v o i d ma i n ( )
{
i nt i , j , k ;

i f C ! _s e t v i d e omod e C _M R E S4C O L O R
{
p r i n t f C " N o pa l ettes a v a i l a b l e " ) ;
exi t ( 1 ) ;
_selectpalette 644

for ( i = 0 ; i < 4 ; i ++ ) I* P a l e t t e l oo p */
{
_s e l e c t p a l e t t e ( i ) ;
for ( k = 0 ; k < 8 ; k++ I* B a c k g round c o l o r l oop * /
{
_c l ea r s c reen ( _GC LEARSC R E E N ) ;
_s e t b k c o l o r ( b k c o l o r [ k ] ) ;
_s e t t e x t p o s i t i on ( 1 , 1 ) ;
p r i n t f ( " Ba c k g round : % s \ t Pa l e t t e : %d " , b k n a me [ k ] , i ) ;
fo r ( j = 1 ; j < 4 ; j ++ > I* Foreg round c o l o r l oop * /
{
_s e t c o l o r ( j ) ;
_e l l i p s e ( _G F I L L I NT E R I O R , 100 , j * 30 , 220 , 8 0 + ( j * 30 ) ) ;
)
g et c h ( ) ;

)
_set v i d eomod e ( _D E FAU LTMO D E ) ;
645 _setactivepage

Description Sets the active page.

#include <graph.h>

short _far _setactivepage( short page );

page Memory page number

Remarks For hardware and mode configurations with enough memory to support multiple screen
pages, _setactivepage specifies the area in memory in which graphics output is written.
The page argument selects the current active page. The default page number is 0.
Screen animation can be done by alternating the graphics pages displayed. Use the
_setvisualpage function to display a completed graphics page while executing graphics
statements in another active page.

These functions can also be used to control text output if you use the text functions
_gettextcursor, _settextcursor, _outtext, _settextposition, _gettextposition,
_settextcolor, _gettextcolor, _settextwindow, and _wrapon instead of the standard
C-language 1/0 functions.

The CGA hardware configuration has only 1 6K of RAM available to support multiple
video pages, and only in the text mode. The EGA and VGA configurations may be
equipped with up to 256K of RAM for multiple video pages in graphics mode.

Return Value If successful, the function returns the page number of the previous active page. If the func­
tion fails, it returns a negative value.

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

See Also _getactivepage, _getvisualpage, _setvisualpage

I * PAGE . C i l l u s t ra t e s v i d e o p a g e fun c t i ons i n c l u d i ng :


* _get a c t i v e p a g e _get v i s u a l p a g e _s et a c t i vepa g e _s et v i s u a l p a g e
*I

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


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

v o i d ma i n ( )
{
s hort o l d v p a g e , o l d a pa g e , p a g e , row , c o l , l i n e ;
s t ruct v i d e o c on f i g v c ;
char b u f [ 80 J ;

_g etv i d e o c o n f i g ( & v c ) ;
i f ( v c . numv i deop a g e s < 4
exi t ( 1 ) : / * Fa i l f o r O S / 2 o r monoc h rome * /
o l d a p a g e = _geta c t i v e p a g e C ) :
o l d v p a g e = _ge t v i s u a l p a ge ( ) ;
_d i s p l a y c u r s o r ( _GC U RSO RO F F ) ;

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 , * /
f o r ( p a g e = 1 : p a g e < 4 : p a g e++ )
{
_s eta c t i v e pa g e ( p a g e ) :
_s ettextpos i t i on C 1 2 , 1 6 * pa g e l :
_o uttext ( " > > > > > > > > " l :

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 to 3 to s h ow mov i ng i ma g e . * /
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 C p a g e ) ;
getc h C l :

I * R e s t o r e o r i g i n a l p a g e ( n o rma l l y 0 ) t o r e s t o r e s c reen . * I
_s eta c t i vepa g e C o l d a p a g e l :
_s et v i s ua l p a g e ( o l d v p a g e ) :
_d i s p l a y c u r s o r_C _GC U RS O RO N ) :
647 _setbkcolor

D.,,,pllan Sets the current background color.

#include <graph.h>

long _far _setbkcolor( long color );

color Desired color

R1ma"'8 The _setbkcolor function sets the current background color to the color value color.
In a color text mode (such as _TEXTCSO), _setbkcolor accepts (and _getbkcolor returns)
a color index. The value for the default colors is given in a table in the description of the
_settextcolor function. 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 is green in a color text mode.

In a color graphics mode (such as _ERESCOLOR), _setbkcolor accepts (and _getbkcolor


returns) a color value. The value for the background color is given by the manifest con­
stants defined in the GRAPH.H include file. For example, _setbkcolor( _GREEN) sets the
background color in a graphics mode to green. These manifest constants are provided as a
convenience in defining and manipulating the most common colors. The actual range of
colors is, in general, much greater.

In general, 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.
Since the background color is color index 0, the _remappalette function will act identi­
cally to the _setbkcolor function. Unlike _remappalette, however, _setbkcolor does not
require an EGA or VGA environment.

In a text mode, the _setbkcolor function does not affect anything already appearing on the
display; only the subsequent output is affected. In a graphics mode, it immediately changes
all background pixels.

R,,,,,,.,, Value In text modes, setbkcolor returns the color index of the old background color. In graphics
modes, _setbkcolor returns the old color value of color index 0. There is no error return.

Campallblllly D ANSI B DOS B OS/2 D UNIX D XEN IX

811 A/80 _getbkcolor, _remappalette, _selectpalette

Example See the example for _getcolor.


setbuf 648

Description Controls stream buffering.

#include <Stdio.h>

void setbuf( FILE *stream, char *buffer );

stream Pointer to FILE structure

buffer User-allocated buffer

Rematks The setbuf function allows the user to control buffering for stream. The stream argument
must refer to an open file that has not ·been read or written. If the buffer argument is NULL,
the stream is unbuffered. If not, the buffer must point to a character array of length
BuFSIZ, where BUFSIZ is the buffer size as defined in STDIO.ff. The user-specified buff­
er, instead of the default system-allocated buffer for the given stream, is used for 1/0
buffering.

The stderr and (in DOS only) stdaux streams are unbuffered by default, but may be as­
signed buffers with setbuf.

The setbuf function has been subsumed by the setvbuf function, which should be the pre­
ferred routine for new code. The setbuf function is retained for compatibility with ex­
isting code.

Retum Value None.

Compatibility • ANSI • DOS • 0812 • UNIX • XENIX

See Also fclose, mush, fopen, setvbuf

Exampm ��������-

1 * S ETBU F . C : T h i s p r o g r a m fi r s t open s f i l e s n a med DATA l a nd DATA2 .


* T h e n i t u s e s s e t b u f t o g i v e DATA l a u s e r - a s s i gned buffer
* a n d t o c h a n g e DATA2 s o that i t has n o buffe r .
*I

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

v o i d ma i n ( )
{
c h a r b u f [ B U FS I Z ] ;
F I L E * s t r e a m l , * s t ream2 ;
649 setbuf

i f ( ( ( s t reaml = fopen ( " d a t a l • , • a • ) ) ! = N U L L ) &&


C C s t r e a m2 = fopen C " d a t a 2 " , • w • ) ) ! = N U L L ) >

I * " s t r e a m l " u s e s u s e r - a s s i gned b u f fe r : * /


s et b u f ( s t reaml , b u f ) ;
p r i n t f C " s t reaml s e t t o u s e r - d e f i n e d b u f f e r a t : % F p \ n " , b u f ) ;

/ * " s t re a m2 " i s u n b u ffered */


s etb u f C s t ream2 , N U L L ) ;
p r i n t f ( " s t ream2 buffe r i ng d i s a b l ed \ n " ) ;
fcl osea 1 1 ( ) ;

Output

s t r e a m l s e t t o u s e r - d e f i ned buffer a t : 0298 : 0 D F2


s t r e a m2 buffe r i n g d i s a b l ed
_setcliprgn Bsa

D11crlptlon Sets the clipping region for graphics.

#include <graph.h>

void _far _setcliprgn( short xi, short y i, short x2, short y2 );

xi , yi Upper-left comer of clip region

x2, y2 Lower-right comer of clip region

Remarks The _setcliprgn function limits the display of subsequent graphics output and font text out­
put to an area of the screen called the "clipping region." The physical points (xi, yi) and
(x2, y2) are the diagonally opposed sides of a rectangle that defines the clipping region.
This function does not change the view coordinate system. Rather, it merely masks the
screen.

Note that the _setcliprgn function affects graphics and font text output only. To mask the
screen for text output, use the _settextwindow function.

Retum Value None.

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

See Also _settextwindow, _setvieworg, _setviewport, _setwindow

&amp• �����

I * S C L I P RGN . C * /
#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 >
#i n c l u d e < g r a p h . h >

v o i d ma i n ( )
{
/ * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i deomod e ( _MAX R E S M O D E )
exi t C 1 ) ;

/ * Set c l i p r e g i o n , t h e n d ra w a n d e l l i p s e l a rg e r t h a n · t h e reg i on . * /
_s etc l i p r g n C 0 , 0 , 200 , 1 2 5 > :
_el l i p s e ( _G F I L L I NT E R I O R , 80 , 50 , 240 , 1 9 0 ) ;
651 _setcliprgn

getch ( ) ;
_s et v i d eomod e ( _ O E FAU LTM O D E ) ;
_setcolor 652

Description Se� the current color.

#include <graph.h>

short _far _setcolor( short color );

color Desired color index

Remarks The _setcolor function sets the current color index to color. The color parameter is
masked but always within range. The following graphics functions use the current color:
_arc, _ellipse, _ftoodfill, _lineto, _outgtext, _pie, _rectangle, and _setpixel.
The _setcolor function accepts an int value as an argument. It is a color index.
The default color index is the highest numbered color index in the current palette.
Note that the _setcolor function does not affect the output of the presentation-graphics
functions.

Return Value This function returns the previous color. If the function fails (e.g., if used in a text mode),
it returns - 1 .

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

See Also _arc functions, _ellipse functions, _ftoodfill, _getcolor, _lineto functions, _outgtext,
_pie functions, _rectangle functions, _selectpalette, _setpixel functions

I * G P I X E L . C : T h i s p r o g r a m a s s i g n s d i fferent c o l o r s t o r a n d oml y
* s e l ected pi xel s .
*I

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


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

v o i d ma i n ( )
(
s h o r t x v a r , yv a r :
s t r u c t v i deocon f i g v c :
1sa _setcolor

I * F i nd a va l i d g r a p h i c s mode . * /
i f ( ! _s e t v i d eomode ( _MA X C O LORMODE ) )
ex i t ( 1 ) ;
_g et v i d e o c on f i g ( &vc > :

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 rta i n pi x e l s . * /
_e l l i ps e ( _G F I L L I NT E R I O R , vc . n umx p i x e l s I 6 , v c . n umy p i x e l s I 6 ,
vc . n umx p i x e l s I 6 * 5 , vc . numyp i xel s I 6 * 5 );

I * D r a w ra ndom p i x e l s i n ra ndom c o l o r s . . . * I
whi l e ( ! kbhi t ( ) )
{
I * . . . but o n 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 ( ) % vc . numx p i x e l s ;
y v a r = r a nd ( ) % vc . numy p i x e l s ;
i f ( _g et p i x e l ( x v a r , yv a r ) ! = 0
{
_s e t c o l o r ( r a n d ( ) % 1 6 ) ;
_s e t p i x e l C x v a r , y v a r > :

getch ( ) ; / * T h row away t h e keys t r o k e . * /


_s e t v i d eomod e ( _D E FAU LTM O D E · > :
_setfillmask 654

Description Sets the fill mask.

#include <graph.h>

void _far _setfdlmask( unsigned char _far *mask );

mask Mask array

Remarks The _setfillmask function sets the current fill mask, which determines the fill pattern. The
mask is an 8-by-8 array of bits in which each bit represents a pixel. A 1 bit sets the corre­
sponding pixel to the current color, while a 0 bit leaves the pixel unchanged. The pattern is
repeated over the entire fill area.
If no fill mask is set (mask is NULL-the default), only the current color is used in fill
operations.

Return Value None.

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

See Also _ellipse functions, _floodtill, _getfillmask, _pie functions, _rectangle functions

Exampm --------�

/ * G F I L LM S K . C : T h i s p ro g r a m i l l u s t r a t e s _g e t f i l l ma s k a n d _s e t f i l l ma s k . * /

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


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

v o i d e l l i p s ema s k ( s h o r t x l , s h o r t y l , s h o rt x 2 , s h o r t y2 , c h a r _fa r *newma s k ) ;

u n s i g n ed c h a r ma s k l [ 8 ] ( 0x43 , 0x 2 3 , 0x 7 c , 0xf7 , 0x8a , 0x4d , 0x78 , 0x39 } ;


( 0 x l 8 , 0x a d , 0xc0 , 0x7 9 , 0xf6 , 0xc4 , 0xa 8 , 0x23 J ;
=

u n s i gned c h a r ma s k 2 [ 8 ] =
c h a r o l dma s k [ 8 ] ;

v o i d ma i n ( )
[
i nt 1 oop ;

/ * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i d eomod e ( _MA X R E SMO D E )
exi t ( 1 ) ;
655 _seffillmask

I * Set f i r s t f i l l ma s k a n d d ra w rect a n g l e . * /
_s e t f i l l ma s k C ma s k l l ;
_recta n g l e ( _G F I L L I N T E R I O R , 20 , 20 , 100 , 100 ) ;
getch ( ) ;

I * C a l l rout i n e t h a t s a v e s a n d r e s t o r e s ma s k . * /
e l l i p s ema s k ( 60 , 60 , 1 50 , 1 50 , ma s k2 ) ;
getc h ( l ;

I * Ba c k t o o r i g i n a l ma s k . * /
_r e c t a n g l e ( _G F I L L I NT E R I O R , 1 2 0 , 1 2 0 , 190 , 1 9 0 l ;
getch C l ;

_s et v i d e omod e C _D E FAU LTMO D E l ;

I * D ra w a n e l l i ps e w i t h a s p ec i f i ed f i l l ma s k . * /
v o i d e l l i ps ema s k ( s h ort x l , s h o rt y l , s h o rt x 2 , s h o rt y2 , c h a r _fa r *n ewma s k )
(
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 v ema s k ) ; I* S a v e ma s k *I
_s e t f i l l ma s k C n ewma s k l ; I* Set n ew ma s k *I
_e l l i ps e ( _G F I L L I NT E R I O R , x l , y l , x 2 , y2 ) ; I* U s e n ew ma s k *I
_s e t f i l l ma s k ( s a v ema s k ) ; I* Res t o re o r i g i n a l *I
_selfant 656

D•t:rlpl/on Finds a single font.

#include <grapb.h>

short _far _setfont( unsigned char _far •options );

options String describing font characteristics

Remades The _setfont function finds a single font, from the set of registered fonts, that has the char­
acteristics specified by the options string. If a font is found, it is made the current font. The
current font is used in all subsequent calls to the _outgtext function. There can be only one
active font at any time.
The options string is a set of characters that specifies the desired characteristics of the font.
The _setfont function searches the list of registered fonts for a font matching the specified
characteristics.
The characteristics that may be specified in the options string are shown in the list below.
Characteristics specified in the options string are not case- or position-sensitive.

Characteristic Description

t'fontname' T}'peface.

bx Character height, where x is the number of pixels.

wy Character width, where y is the number of pixels.


f Find only a fixed-space font (should not be used with the
p characteristic).
p Find only a proportionally spaced font (should not be used
with the f characteristic).

v Find only a vector font (should not be used with the r


characteristic).
r Find only a raster-mapped (bit-mapped) font (should not be
used with the v characteristic).
b Select a best fit font.
DX Select font number x, where x is less than or equal to the value
returned by the _registerfonts function. Use this option to
"step through" an entire set of fonts.
657 _setfont

You can request as many options as desired, except with nx, which should be used alone.
If mutually exclusive options are requested (such as the pair f/p or r/v), the _setfont func­
tion ignores them. There is no error detection for incompatible parameters used with nx.

Options can be separated by blanks in the options string. Any other character is ignored by
_setfont
The t (the typeface specification) in options is specified as a "t" followed by fontname in
single quotes. Choosefontname from the following list:

Fontname Description

Courier Fixed-width bit-mapped font with serifs


Helv Sans serif proportional bit-mapped font
Tms Rrnn Proportional bit-mapped font with serifs
Script Proportional vector-mapped font of slanted characters formed
from nearly continuous lines
Modem Proportional vector-mapped font without serifs
Roman Proportional vector-mapped font with serifs

A b in the options field causes the _setfont routine to automatically select the "best fit"
font that matches the other characteristics you have specified. If the b parameter is spec­
ified and at least one font is registered, _setfont will always be able to set a font and will
return 0 to indicate success.

In selecting a font, the _setfont routine uses the following precedence (rated from highest
precedence to lowest):

I . Pixel height
2. T}'peface

3. Pixel width
4. Fixed or proportional font

You can also specify a pixel width and height for fonts. If a nonexistent value is chosen for
either, and the b option is specified, the _setfont function will chose the closest match. A
smaller font size has precedence over a larger size. If _setfont requests Helv 1 2 with best
fit, and only Helv 1 0 and Helv 14 are available, _setfont will select Helv 1 0.

If a nonexistent value is chosen for pixel height and width, the _setfont function will apply
a magnification factor to a vector-mapped font to obtain a suitable font size. This auto­
matic magnification does not apply if the r (raster-mapped font) option is specified, or if a
specific typeface is requested and no best fit (b) option is specified.
_setfont 658

If you specify the nx parameter, _setfont will ignore any other specified options and
supply only the font number corresponding to x.

Note that the font functions affect only the output from the font output function _outgte:xt;
no other C run-time output functions are affected by font usage.

Retum Value The setfont function returns a 0 to indicate success and a -1 to indicate an error. An
erroroccurs if a request for a specific font fails and the b option was not specified, or if
fonts have not yet been registered.

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

See Also _getfontinfo, _getgtextextent, _outgtext, _registerfonts, _unregisterfonts

Example See the example for _outgtext.


669 _setgtextvector

D11t:tlptlan Changes the orientation of font text output.

#include <graph.h>

struct xycoord _far _setgtextvector( short x, short y );

x, y Integers specifying font rotation

Remarks The _setgtextvector function sets the current orientation for font text output to the vector
specified by x and y. The current orientation is used in calls to the _outgtext function.

The values of x and y define the vector which detennines the direction of rotation of font
text on the screen. The t�xt-rotation options are shown below:

(x, y) Text Orientation

(0, 0) Unchanged

(1 , 0) Horizontal text (default)

(0, 1) Rotated 90 degrees counterclockwise

(- 1 , 0) Rotated 1 80 degrees

(0, -1 ) Rotated 270 degrees counterclockwise

If other values are input, only the sign of the input is used. For example, (-3, 0) is inter­
preted as (-1 , 0).

Relum Value The _setgtextvector function returns the previous vector in a structure of xycoord type. If
you pass the _setgtextvector function the values (0, 0), the function returns the current
vector values in the xycoord structure.

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

SBB Alsa _getfontinfo, _getgtextextent, _grstatus, _outgtext, _registerfonts, _setfont,


_unregisterfonts

Example See the example for _outgtext


setjmp 660

D111t:rlpllon Saves the current state of the program.

#include <Setjmp.h>

int setjmp( jmp_buf env );

env Variable in which environment is stored

Rematts The setjmp function saves a stack environment that can be subsequently restored using
longimp. Used together this way, setjmp and longimp provide a way to execute a "non­
local goto." They are typically used to pass execution control to error-handling or recovery
code in a previously called routine without using the nonnal calling or return conventions.
A call to setjmp causes the current stack environment to be saved in env. A subsequent
call to longjmp restores the saved environment and returns control to the point just after
the corresponding setjmp call. All variables (except register variables) accessible to the
routine receiving control contain the values they had when setjmp was called.

Return Value The setjmp function returns 0 after saving the stack environment. If setjmp returns as a re­
sult of a longimp call, it returns the value argument of longjmp, or, if the value argument
of longimp is 0, setjmp returns 1 . There is no error return.

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

See Also longimp

Example See the example for _fpreset


661 _setlinestyle

Description Sets the line style.

#include <graph.h>

void _far _sedinestyle( unsigned short mask );

mask Desired line-style mask

Rematics Some graphics routines ( _lineto and _rectangle) draw straight lines on the screen. The
type of line is controlled by the current line-style mask.

The _sedinestyle function selects the mask used for line drawing. The mask argument is a
1 6-bit array , where each bit represents a pixel in the line being drawn. If a bit is l , the
corresponding pixel is set to the color of the line (the current color). If a bit is 0, the corre­
sponding pixel is left unchanged. The template is repeated for the entire length of the line.
The default mask is OxFFFF (a solid line).

Relum Value None.

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

See Also _getlinestyle, _lineto functions, _rectangle functions

Example See the example for _gedinestyle.


setlocale 662

Description Defines the locale.

#include <locale.h>

char *setlocale( int category, const char *locale );

category Category affected by locale

locale Name of the locale that will control the specified category

Remades The setlocale function sets the categories specified by category to the locale specified by
locale. The "locale" refers to the locality (country) for which certain aspects of your pro­
gram can be customized. Some locale-dependent aspects include the fonnatting of dates
and the display fonnat for monetary values.

The setlocale function is used to set or get the program's current entire locale or simply
portions of the locale infonnation. The category argument specifies which portion of a pro­
gram's locale infonnation will be used. The manifest constants used for the category argu­
ment are listed below:

Category Parts of Program Affected

LC_ALL All categories listed below.

LC_COLLATE The strcoll and strxfrm functions.

LC_CTYPE The character-handling functions (except for isdigit and


isxdigit, which are unaffected).
LC_MONETARY Monetary fonnatting infonnation returned by the localeconv
function.

LC_NUMERIC Decimal point character for the fonnatted output routines


(such as printf), for the data conversion routines, and for
the nonmonetary fonnatting infonnation returned by the
localeconv function.
LC_TIME The strftime function.

The locale argument is a pointer to a string that specifies the name of the locale. If
locale points to an empty string, the locale is the implementation-defined native environ­
ment. A value of "C" specifies the minimal ANSI confonning environment for C transla­
tion. This is the only locale supported in Microsoft C, version 6.0.
If the locale argument is a null pointer, setlocale returns a pointer to the string associated
with the category of the program's locale. The program's current locale setting is not
changed.
663 setlocale

Return Value If a valid locale and category are given, _setlocale returns a pointer to the string associated
with the specified category for the new locale. If the locale or category is invalid, the
setlocale function returns a null pointer and the program's current locale settings are not
changed.

The pointer to a string returned by setlocale can be used in subsequent calls to restore that
part of the program ' s locale infonnation. Later calls to setlocale will overwrite the string.

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

S11 Al60 localec:onv, strcoll, strftime, strxfrm


setmode 664

Dest:rlpllan Sets the file translation mode.

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

int setmode ( int handle, int mode );

handle File handle


mode New translation mode

Remades The setmode function sets to mode the translation mode of the file given by handle. The
mode must be one of the following manifest constants:

Constant Meaning

O_TEXT Sets text (translated) mode. Carriage-return-line-feed (CR­


LF) combinations are translated into a single line-feed (LF)
character on input. Line-feed characters are translated into CR­
LF combinations on output.
O_BINARY Sets binary (untranslated) mode. The above translations are
suppressed.
'
The setmode function is typically used to modify the default translation mode of stdio,
stdout, stderr, stdaux, and stdprn, but can be used on any file. If setmode is applied to
the file handle for a stream, the setmode function should be called before any input or out­
put operations are performed on the stream.

Return Value If successful, setmode returns the previous translation mode. A return value of -1 indi­
cates an error, and errno is set to one of the following values:

Value Meaning

EBADF Invalid file handle


EINVAL Invalid mode argument (neither O_TEXT nor O_BINARY )

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


665 setmode

SBB A/sa creat, fopen, open

I * S ETMODE . C : Th i s p r o g r a m u s e s s etmode to c h a n g e s td i n f r om text


* mode t o b i na ry mod e .
*I

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

v o i d ma i n < >
{
i n t res u l t ;

I * Set " s t d i n " to h a v e b i na ry mode : * I


res u l t = s etmod e ( f i l en o ( s td i n ) , O_B I NA RY ) ;
i f ( res u l t -= -1 )
p e r ro r ( " C a n not s e t mod e " ) ;
el se
p r i n t f ( " ' s t d i n ' s u c c e s s fu l l y c h a nged t o b i n a ry mod e \ n " ) ;

Output

' s t d i n ' s u c c e s s fu l l y c h a n g ed to b i n a ry mod e


_setpixel Functions 666

Descr/pUan Set a pixel to the current color.

#include <graph.h>

short _far _setpixel( short x, short y );


short _far _setpixel_w( double wx, double wy ) ;

xy, Target pixel

wx, wy Target pixel

Rematlrl The _setpixel and the _setpixel_w functions set a pixel at a specified location to the
current color.

The _setpixel function sets the pixel at the view-coordinate point (x, y) to the current color.

The _setpixel_w function sets the pixel at the window-coordinate point (wx, wy) to the
current color.

Retum Value The function returns the previous value of the target pixel. If the function fails (for ex­
ample, the point lies outside of the clipping region), it will return - 1 .

CampaUblltty 0 ANSI • DOS 0 0812 0 UNIX 0 XENIX

See A/10 _getpixel functions, _setcolor

I * G P I X E L . C : T h i s p r o g r a m a s s i g n s d i fferent c o l o r s t o r a n d oml y
* s e l ected p i x e l s .
*I

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


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

v o i d . ma i n ( )
I
s ho r t x va r , y v a r ;
s t ruct v i d e o c on f i g v c ;
667 _setpixel Functions

I * F i nd a v a l i d g r a p h i c s mode . * /
i f { ! _s e t v i d eomode { _MA X C O LORMODE ) )
exi t < 1 ) :
_g et 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 r t a i n p i x e l s . * /
_e l l i ps e { _G F I L L I N T E R I O R , vc . n umxp i x e l s I 6 , vc . n umyp i x e l s I 6 ,
vc . n umxp i x e l s I 6 * 5 , vc . numyp i xel s I 6 * 5 ) ;

/ * D r a w ra n d om p i x e l s i n r a n d om c o l o r s . . . * /
w h i l e { ! kb h i t { ) )
(
I * . . . b u t on l y i f t h ey a r e 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 nd { ) % v c . n umxp i xe l s ;
y v a r = r a nd < > % vc . 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 ( ) % 16 > :
_s e t p i x e l ( x v a r , y v a r > :

getc h ( ) ; / * Th row away t h e keys t ro k e . * /


_s e t v i d eomod e ( _D E FAU LTM O D E ) ;
_settextcolor 668

Description Sets the current text color.

#include <graph.h>

short _far _settextcolor( short index );

index Desired color index

Rematfcs The _settextcolor function sets the current text color to the color index specified by index.
The default text color is the same as the maximum color index.
The settextcolor routine sets the color for the outtext and outmem functions only. It
doesnot affect the color of the printf function or the color oftext output with the
_outgtext font routine. Use the _setcolor function to change the color of font output.
In text color mode, you can specify a color index in the range 0 -3 1 . The colors in the
range 0 - 1 5 are interpreted as normal (non-blinking). The normal color range is defined
below:

Index Color Index Color

0 Black 8 Dark gray


Blue 9 Light blue
2 Green 10 Light green
3 Cyan 11 Light cyan
4 Red 12 Light red
5 Magenta 13 Light magenta
6 Brown 14 Yellow
7 White 15 Bright white

Blinking is selected by adding 16 to the normal color value.


In every text mode, including monochrome, _getvideoconfig 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 sixteen normal colors (0 -15) and sixteen blink­
ing colors ( 1 6 -3 1). Monochrome text mode has fewer unique display attributes, so some
color values 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.

Return Value The function returns the color index of the previous text color. There is no error return.
669 _settextcolor

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

S11 Alsa _gettextcolor, _outtext

I * OUTTXT . C : T h i s examp l e i l l u s t r a t es text o u t p u t func t i o n s :


* _g ettext c o l o r _g e t b k c o l o r _g ettextpos i t i o n _o u t t e x t
* _s ettex t c o l o r _s e t b k c o l o r _s ettextpos i t i o n
*I

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

c h a r buffer [80] ;

v o i d ma i n { )
(

I * S a v e o r i g i n a l f o r e g r o u n d , b a c k g r ound , a n d t e x t po s i t i on * /
s h o r t b l i n k , fgd , o l dfgd ;
l on g bgd , o l dbgd ;
s t ruct rccoord o l d p o s ;

I * S a v 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 text po s i t i on . * /
o l dfgd = _g e t t e x t c o l o r { ) ;
o l d b g d = _g e t b k c o l o r { ) ;
o l d p o s = _g ettextpos i t i on { ) ;
_c l ea r s c reen { _GC L EARSC R E E N ) ;

I * F i r s t t i me n o b l i n k , s econd t i me b l i n k i n g . * /
fo r { b l i n k = 0 ; bl i n k < = 1 6 ; b l i n k += 1 6 )
(
I * Loop t h ro u g h 8 b a c k g round c o l o r s . * /
for { bgd = 0 ; b g d < 8 ; bgd++ )
(
_s e t b k c o l o r { bgd ) ;
_s ettextpos i t i on { { s h o r t ) bgd + { { b l i n k I 1 6 ) * 9 ) + 3 , 1 ) ;
_s e t t e x t c o l o r { 7 ) ;
s p r i n t f C buffe r , " Ba c k : %d F o re : " , bgd ) ;
_ou t t e x t { buffer ) ;
_settextcolor 670

I * Loop t h r o u g h 1 6 foreg round c o l o r s . * /


fo r e fgd = 0 ; fgd < 1 6 ; fgd++ >
{
_s ettextc o l o r ( fgd + bl i n k ) ;
s p r i n t f ( buffe r , " %2d " , fgd + b l i n k ) ;
_outtext C buffer ) ;

I
getch ( ) ;

I * Res t o r e o r i g i n a l foreground , b a c k g ro u n d , a n d text p o s i t i on . * /


_s ettext c o l o r ( o l dfgd ) ;
_se t b k c o l o r ( o l dbgd ) ;
_cl ea r s c reen ( _GC LEARSC 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 ) ;
671 _settextcursar

0181:1'/ptlon Sets the current cursor attribute.

#include <grapb.h>

short _far _settextcursor( short attr );

attr Cursor attribute

R1malkl The _settextcursor function sets the cursor attribute (i.e., the shape) to the value specified
by anr. The high-order byte of attr detennines the top line of the cursor within the charac­
ter cell. The low-order byte of attr detennines the bottom line of the cursor.

The _settextcursor function uses the same fonnat as the BIOS routines in setting the cur­
sor. Typical values for the cursor attribute are listed below:

Attribute Cursor ShaJ!!

Ox.0707 Underline

Ox.0007 Full block cursor

Ox.0607 Double underline

Ox2000 No cursor

Note that this function works only in text video modes.

RBtum Vala• The function returns the previous cursor attribute, or -1 if an error occurs (such as calling
the function in a graphics screen mode).

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

SBB AISO _displaycursor, _gettextcursor

I * D I S C U RS . C : T h i s p r o g r a m c h a n g e s t h e c u r s o r s h a pe u s i n g _gettext c u r s o r
* a n d _settext c u r s o r , a nd h i des t h e c u r s o r u s i n g _d i s p l a y c u r s o r .
*I

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


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

v o i d ma i n ( >
(
s ho r t o l d c u r s o r ;
s h o r t n ewc u r s or = 0x007 ; / * Ful l bl o c k c u r s o r * /

I * S a v e o l d c u r s o r s h a p e a nd ma k e s u re c u r s o r i s on . * /
ol dcursor = _get t e x t c u r s o r ( } ;
_c l ea r s c reen ( _GC L EARSC R E E N } ;
_d i s p l ay c u rs o r ( _GC U RSORO N } ;
_o ut t e x t < " \ nO l d c u r s o r s h a pe : " ) ;
getch ( l ;

I * C h a n g e c u r s o r s h a pe . * /
_out t ex t ( " \ n N ew c u r s o r s h a pe : " l ;
_s e t t ex t c u r s o r ( n ewc u r s o r } ;
getch ( ) ;

/ * Re s t o r e o r i g i n a l c u r s o r s h a p e . * /
_ou t t ex t ( " \ n " ) ;
_s e t t ex t c u r s o r ( o l d c u r s o r ) ;
673 _settextposition

Dacrlptlan Sets the text position.

#include <graph.h>

struct rccoord _far _settextposition( short row, short column );

row, column New output start position

Remadts The _settextposition function sets the current text position to the display point
(row, column). The outtext and outmem functions (and standard console 1/0 routines,
such as printf) output text at that point.

The rccoord structure, defined in GRAPH.ff, contains the following elements:

Element Description
short row Row coordinate
short col Column coordinate

Return Value The function returns the previous text position in an rccoord structure, defined in
GRAPH.ff.

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

See Also __gettextposition, _outtext, _settextwindow

I * OUTTXT . C : T h i s exampl e i l l u s t r a t e s text o u t p u t func t i o n s :


* _ge t t ex t c o l o r _g e t b k c o l o r _g ettextpos i t i on _ou t t ext
* _s e t t ex t c o l o r . _s et b k c o l o r _s ettextpo s i t i on
*/

#i n c l ude < 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 < g r a p h . h >

c h a r bu ffe r ( 80 ] :

v o i d ma i n ( )
(
_settextposition 114

I* S a v e o r i g i n a l f o r e g r o u n d , b a c kg r o u n d , a nd t e x t p o s i t i o n */
s h o r t b l i n k , fgd , o l d fgd ;
l ong bgd , o l d b g d ;
s t r u c t r c c o o rd· o l d p o s ;

I * S a v e o r i g i n a l f o r e g r o u n d , b a c k g ro u n d , a nd text p o s i t i on . */
o l d f g d a _g e t tex t c o l o r ( ) ;
o l d b g d = _g e t b k c o l o r C > ;
o l d p o s m _g e t t e x t p o s i t i on ( ) ;
_c l e a r s c r e e n ( _GC LEARSC R E E N ) ;

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 e b l i n k = 0 ; b l i n k <- 1 6 ; b l i n k +- 1 6 >
I
I * Loop t h r o u g h 8 b a c kg ro u n d 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 C bgd ) ;
_s e t t e x t p o s i t i on C C s h o r t ) bg d + ( ( b l i n k I 1 6 ) * 9) + 3 , 1 >:
_s e t t e x t c o l o r C 7 > ;
s p r i n t f C b u f fe r , " B a c k : Sd F o r e : • , bgd > :
_o u t t ex t C b u f f e r ) ;

/ * Loop t h ro u g h 1 6 f o r e g r o u n d c o l o r s . */
f o r ( f g d = 0 ; f g d < 1 6 ; f gd++ >
(
_s e t t e x t c o l o r C fgd + b l i n k > :
s p r i n t f ( b u f f e r , • S 2 d • , fg d + b l i n k > :
_o u t t e x t ( b u f f e r ) ;

)
getc h C ) ;

I * R e s t o 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 ro u n d , a n d t e x t po s i t i on . */
_s e t t e x t c o l o r ( o l d f g d ) ;
_s e t b k c o l o r ( o l d b g d ) ;
_c l e a r s c r e e n C _GC L EA R S C R E E N ) ;
_s e t t e x t p o s i t i on C o l d p o s . row , o l d p o s . c o l ) ;
675 _settextrows

Dnt:l'lpl/an Sets the number of screen rows for text modes.

#include <graph.h>

short _far _settextrows( short rows );

rows Number of text rows

The _settextrows function specifies the number of screen rows to be used in text modes.

If the constant MAXTEXTROWS is specified for the rows argument, the function
_

will choose the maximum number of rows available. In text modes, this is 50 rows on
VGA, 43 on EGA, and 25 on others. In graphics modes that support 30 or 60 rows,
_MAXTEXTROWS specifies 60 rows.

Rstum Value This function returns the numbers of rows set. The function returns 0 if an error occurred.

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

SBB AIBD _getvideoconfig, _setvideomode, _setvideomoderows

I * STXTROWS . C : T h i s p r o g r a m a tt empts to set t h e s c reen h e i g h t . I t ret u r n s


* a n e r r o r l e v e l c o d e of 1 ( fa i l ) o r 0 ( s u c c es s ) t h a t c o u l d be t e s t e d i n
* a batch fi l e .
*I

#i n c l u d e < g r a p h . h>
#i n c l u d e < s t d l i b . h>

v o i d ma i n ( i n t a rg c , c h a r **a rgv )
(
s h o r t rows ;

i f ( ! C rows = a t o i C a rg v [ l ] ) ) >
(
_outtext < " \ nSyn t a x : STXTROWS [ 25 I 43 I 50 J \ n " ) ;
exi t < 1 ) ;
_settextrows 676

I * M a ke s u re n ew rows a re t h e s a me a s r e q u e s ted rows . * /


i f ( _s e t t e x t rows C rows > ! = rows )
(
_ou t t e x t C " \ n l n v a l i d rows \ n " ) ;
ex i t C 1 > ;
}
el se
exi t C Ill >;
677 _settextwindow

Oner/pt/an Creates a text window.

#include <graph.h>

void _far _settextwindow( short rl , short cl , short r2, short c2 );

rl, cl Upper-left comer of window

r2, c2 Lower-right comer of window

Remades The _settextwindow function specifies a window in row and column coordinates where
all text output to the screen is displayed. The arguments (r1, cl) specify the upper-left
comer of the text window, and the arguments (r2, c2) specify the lower-right comer of the
text window.

Text is output from the top of the text window down. When the text window is full, the
uppermost line scrolls up out of it.

Note that this function does not affect the output of presentation-graphics text (e.g., labels,
axis marks, etc.). It also does not affect the output of the font display routine _outgtext
Use the _setviewport function to control the display area for presentation graphics or
fonts.

Retum Value None.

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

See Also _gettextposition, _gettextwindow, _outtext, _settextposition

Example See the example for _scrolltextwindow.


setvbuf 678

DBScrlptlon Controls stream buffering and buffer size.

#include <Stdio.h>

int setvbuf( FILE *stream, char *buffer, int mode, size_t size );

stream Pointer to FILE structure

buffer User-allocated buffer

mode Mode of buffering: _IOFBF (full buffering), _IOLBF (line


buffering), _IONBF (no buffer)

size Size of buffer

Remarks The setvbuf function allows the program to control both buffering and buffer size for
stream. The stream must refer to an open file that has not been read from or written to
since it was opened. The array pointed to by buffer is used as the buffer, unless it is NULL,
and an automatically allocated buffer size bytes long is used.

is used as the size of the buffer. If mode iS _IONBF, the stream is unbuffered and size and
The mode must be IOFBF, IOLBF, or IONBF. If mode is IOFBF or IOLBF, then size

buffer are ignored.


Values for mode and their meanings are:

Type Meaning
_IOFBF Full buffering; that is, buffer is used as the buffer and size is
used as the size of the buffer. If buffer is NULL, an automat­
ically allocated buffer size bytes long is used.

_IOLBF Under DOS and OS/2, the same as _IOFBF.

_IONBF No buffer is used, regardless of buffer or size.

The legal values for size are greater than 0 and less than 32,768.

Return Value The return value for setvbuf is 0 if successful, and a nonzero value if an illegal type or
buffer size is specified.
619 setvbuf

Campatlbll/ly 8 ANSI a DOS 8 OS/2 8 UNIX 8 XENIX

See Also fclose, mush, fopen, setbuf

I * S ETVBU F . C : T h i s p r o g r a m opens two s t reams n a med s t reaml a n d s t ream2 .


* I t t h e n u s e s s et v b u f t o g i v e s t reaml a u s e r - d e f i ned buffer of 1024
* byt e s a n d s t ream2 n o buffe r .
*/

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

voi d ma i n ( )
(
c h a r b u f [ 1024 J ;
F I L E * s t r e a m l , *st ream2 ;

i f ( C C s t r e a m l = fopen ( " d a t a l " , • a • > > ! = N U L L ) &&


( ( s t ream2 - fopen ( " d a t a 2 " , • w • ) ) ! = N U L L > )

i f ( setvbuf( st reaml , buf , _I O FB F , s i zeof ( b u f > > ! = 0 )


p r i n t f ( " I n c o r re c t type o r s i z e of buffer for s t reaml \ n " ) ;
el se
pri ntf( " ' st reaml ' n ow h a s a buffer of 1 0 2 4 byt e s \ n " ) ;
i f ( s e t v b u f ( s t ream2 , N U L L , _I O N B F , 0 ) ! = 0 )
p r i n t f ( " I nc o r re c t type o r s i z e of b u f f e r for s t ream2 \ n " ) ;
el se
p r i n t f ( " ' s t ream2 ' n o w h a s n o buffe r \ n " ) ;
fc l os ea l l C ) ;

Output

' s t re a m l ' now h a s a b u f f e r o f 1024 byt e s


' s t ream2 ' n o w h a s no b u f f e r
_setvideomode 680

OlllJl'/ptlan Sets the video mode.

#include <graph.h>

short _far _setvideomode( short mo4e );

mode Desired mode

R1matks The _setvideomode function selects a screen mode appropriate for a particular hard-
ware/display configuration. The mode argument can be one of the manifest constants
shown in Table R.9 and defined in GRAPH.ff.

Table R.9 Manifest Constants for Screen Mode

Mode Type 1 Size2 Colors3 Adapter


4

D FAULTMODE
_ E Hardware default
mode
A
_M XRESMO E D Highest resolution
in graphics mode
A
_M XCOLORMO E D M aximum colors
in graphics mode
T
_ EXT W 0B 4 Mrr 40 x 25 16 eGA

X B
_TEXTC40 err 40 x 25 16 eGA
_TE T W80 Mrr 80 x 25 16 eGA

MRES4COLOR
_TEXTC80 err 80 x 25 6 eGA

_MRESNOCOLOR
_ C/G 3 20 x 200 4 eGA
MIG 320 x 200 4 CGA

T XT
_HRESBW MIG 640 x 200 2 eGA
_ E MONO Mrr 80 x 25 MDPA
5
_HERCMON0 Hercules graphics 720 x 348 HGe
_MRES16COLOR e/G 320 x 200 16 EGA
_HRES16COLOR e/G 640 x 200 16 EGA
_ERESNOCOLOR Mrr 640 x 350 EGA
_ERESCOLOR C/G 640 x 350 16 EGA
681 _setvideomode

Table R.9 (continued)


1 2 4
Mode Type Size Colors3 Adapter

_VRES2COLOR C/G 640 x 480 2 VGA


_VRES16COLOR C/G 640 x 480 16 VGA
_MRES256COLOR C/G 320 x 200 256 VGA
_ORESCOLOR C/G 640 x 400 1 of 1 6 OLIY

1. M indicates monochrome, C indicates color output, T indicates text, and G indicates graphics generation.
2. For texl modes , size is given in characters (columns
·
x rows). For graphics modes, size is given in pixels
(horizonlal x vertical).
3. For monochrome displays, lhe number of colors is lhe number of gray shades.
4. Adapters are lhe IBM (and compatible) Monochrome Adapter (MDPA), Color Graphics Adapter (CGA),
Enhanced Graphics Adapter (EGA), Video Graphics Array (VGA), Hercules-compatible adapter (HGC), and
Olivelli-compatible adapter (OLIV).
5. ln _HERCMONO mode, lhe texl dimensions are 80 columns by 25 rows, wilh a 9 by 14 characler box. The
bottom IWo scan lines of row 25 are nol visible.

Note that only standard hardware is described here, but display hardware that is strictly
compatible with IBM, Hercules, or Olivetti hardware should also work as described.

_MAXRESMODE and The two special modes _MAXRESMODE and _MAXCOLORMODE select the highest reso­
_MAXCOLORMODE
lution or greatest number of colors available with the current hardware, respectively.
These two modes fail for adapters that do not support graphics modes.

Table R. 1 0 lists the video mode selected for different adapter and monitor combinations
when _MAXRESMODE or _MAXCOLORMODE is specified:

Table R.10 Modes Selected by _MAXRESMODE and _MAXCOLORMODE

Adapter/Monitor _MAXRESMODE _MAXCOLORMODE


MDPA fails fails
HOC _HERCMONO _HERCMONO

CGA color* _HRESBW _MRES4COLOR

CGA noncolor* _HRESBW _MRESNOCOLOR

OCGA _ORESCOLOR _MRES4COLOR

OEGA color _ORESCOLOR _ERESCOLOR

EGA color 256K _HRES16COLOR _HRES16COLOR

EGA color 64K _HRES16COLOR _HRES16COLOR


_setvideomode 682

Table R.10 (co11ti11ued)

Adapter/Monitor _MAXRESMODE _MAXCOLORMODE

EGA ecd 256K _ERESCOLOR _ERESCOLOR

EGA ecd 64K _ERESCOLOR _HRES16COLOR

EGA mono _ERESNOCOLOR _ERESNOCOLOR

MCGA _VRES2COLOR _MRES256COLOR

VGA _VRES16COLOR _MRES256COLOR

OVGA _VRES 16COLOR _MRES256COLOR

* Color monitor is assumed if the start-up text mode was TEXTC80 or TEXTC40 or if the start-up mode
was graphics mode. Composite or other noncolor CGA monitor is assumed if start-up mode was TEXTBW80 or
TEXTBW40.

Hercules Support You must install the Hercules driver MSHERC.COM before running your program. Type
MSHERC to load the driver. This can be done from an AUTOEXEC.BAT file.
If you have both a Hercules monochrome card and a color video card, you should install
MSHERC.COM with the /H (/HALF) option. The /H option causes the driver to use one
instead of two graphics pages. This prevents the two video cards from attempting to use
the same memory. You do not have to use the /H option if you have only a Hercules card.
See your Hercules hardware manuals for more details of compatibility.

To use a mouse, you must follow special instructions for Hercules cards in Microsoft
Mouse Programmer's Reference Guide. (This is sold separately; it is not supplied with
either Microsoft C or the mouse package.)

Return Value The function returns the number of text rows if the function is successful. If an error is en­
countered (that is, the mode selected is not supported by the current hardware configura­
tion), the function returns 0.

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

In OS/2, only text video modes may be selected by _setvideomode.

See Also _getvideoconfig, _settextrows, _setvideomoderows

Exampm --
----�

/ * S V I DMO D E . C : Th i s p r o g r a m s e t s a v i deo mode f rom a s t r i n g g i ven on t h e


* c omma nd l i n e .
*I
683 _setvideomode

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

s h o r t mod e s [ ] = { _T E XTBW40 , _T E XTC40 , _T EXTBW80 ,


_T E X TC80 , _M RES4COLO R , _M RESNOCO LO R ,
_H R E S BW , _T EXTMONO , _H E RCMO N O ,
_M R E S 1 6 C O LO R , _H R E S 1 6 C O LO R , _ERESNOCO LO R ,
_E R E S C O LO R , _V RES2COLO R , _V RES 1 6 C O LO R ,
_M R E S 2 5 6 C O LOR , _O R E S C O L O R
):
c h a r *names [ ] = { " T E XTBW40 " , " T EXTC40 " , " T EXTBW80 " ,
" T E XTC80 " , " M R E S4CO LOR " , " M RESNOCO L O R " ,
" H RE S BW " , " T E XTMONO " , " H E RCMONO " ,
" M RE S 1 6 C O L O R " , " H RE S 1 6 C O L O R " , " E RESNOCO LO R " ,
" E RE S C O LO R " , " V R E S 2 C O LO R " , " V RE S 1 6 C O LO R " ,
"MRES256COLOR" , " O R E S C O LO R "
):

v o i d e r ro r ( c h a r *ms g ) ;

v o i d ma i n ( i n t a rg c , c h a r *a rgv [ ]
{
s h o r t i , n u m = s i z e o f ( modes ) I s i zeof C s h o rt ) ;
s t ruct v i deoconfi g vc ;

i f ( a rg c < 2 )
e r r o r ( " N o a rg ument g i ven " > :

I * I f ma t c h i n g name found , c h a n g e t o co r r e s p o n d i n g mod e . * /


for ( i = 0 ; i < n um ; i ++ )
{
i f ( ! s t rcmp i C a rg v [ l ] , names [ i ] ) )
{
_s et v i d eomod e C mod e s [ i ] ) ;
_o u t t e x t C " N ew mode i s : • ) ;
_ou t t ex t < n a me s [ i ] > :
exi t ( 0 ) ;

)
e r r o r ( " I n v a l i d mode s t r i n g " ) ;

v o i d e r ro r ( c h a r *ms g
[
_ou t t ex t C m s g ) ;
ex i t C 1 ) ;
_setvideomoderows 684

Description Sets the video mode and number of text rows for text modes.

#include <graph.h>

short _far _setvideomoderows( short mode, short rows );

mode Desired mode

rows Number of text rows

Remarks The _setvideomoderows function selects a screen mode for a particular hardware/display
combination. The manifest constants for the screen mode are given in the reference pages
for _setvideomode. The _setvideomoderows function also specifies the number of text
rows to be used in a text mode. If the constant _M AXTEXTROWS is specified for the rows
argument, the function will choose the maximum number of rows available. In text modes,
this is 50 rows on VGA, 43 on EGA, and 25 on others. In graphics modes that support 30
or 60 rows, _MAXTEXTROWS specifies 60 rows.

Return Value The setvideomoderows function returns the numbers of rows set. The function returns 0 if
an error occurred (e.g., if the mode is not supported).

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

In OS/2, only text video modes may be selected by _setvideomoderows.

See Also _getvideoconfig, _settextrows, _setvideomode

Exampre ������
I * S V M ROWS . C * /

#i n c l u d e < s t d l i b . h >
#i n c l ude < c o n i o . h >
#i n c l ude < g r a p h . h >

v o i d ma i n ( )
(
s t r u c t v i deocon f i g c o n f i g ;
685 _setvideomoderows

I * Set 4 3 - l i n e g r a p h i c s mode i f a v a i l a b l e . * /
i f ( ! _s et v i d eomod e r ow s C _ERESCOLO R , 43 > >
{
_o uttext ( " EGA o r V GA requ i red " ) ;
exi t ( 1 ) ;
)
_get v i d eo c on f i g ( & c o n f i g ) ;

I * Set l og i c a l o r i g i n t o c e n t e r � nd d ra w a rect a ng l e . * /
_s et l o g o r g ( c o n f i g . n umxp i xel s I 2 - 1 , c o n f i g . n umy p i x e l s I 2 - 1 ) ;
_rect a n g l e ( _GBORD E R , - 80 , - 50 , 80 , 50 ) ;

getch ( ) ;
_s e t v i d eomod e ( _D E FAU LTMOD E ) ;
· _setvieworg 686

Description Moves the view-coordinate origin to the specified physical point.

#include <graph.h>

struct xycoord _far _setvieworg( short x, short y );

x, y New origin point

Remarks The _setvieworg function moves the view-coordinate origin (0, 0) to the physical point
(x, y). All other view-coordinate points move the same direction and distance.

The xycoord structure, defined in GRAPH.H, contains the following elements:

Element Description

short xcoord x coordinate


short ycoord y coordinate

C 5. 1 Difference This function replaces the _setlogorg function.

Return Value The function returns the physical coordinates of the previous view origin in an xycoord
structure, defined in GRAPH.H.

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

See Also _getphyscoord, _getviewcoord, _getwindowcoord, _setcliprgn, _setviewport

/ * S V O RG . C : T h i s p r o g r a m s et s t h e v i ew o r 1 g 1 n t o t h e c e n t e r of
* the s c reen , then d r aws a rect a n g l e u s i n g the n ew o r i g i n .
*I

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


#i n c l ude < c on i o . h >
#i n c l ude < g ra p h . h >

v o i d ma i n ( )
{
s t r u c t v i deocon f i g c o n f i g ;
687 _setvieworg �

I * F i n d a v a l i d g r a p h i c s mode . * I
i f ( ! _set v i d e omod e ( _MA X RESMO D E )
exi t ( 1 > :
_g et v i d e o c o n f i g ( & c o n f i g ) ;

I * Set v i ew o r i g i n t o t h e c e n t e r of t h e s c reen . * /
_s et v i eworg ( c o n f i g . n umxp i x e l s I 2 , c o n f i g . n umy p i xel s I 2 ) ;
_rec t a n g l e ( _GBO R D E R , -80 , - 50 , 80 , 50 ) ;

getc h ( > ;
_s e t v i deomod e ( _D E FAU LTMOD E ) ;
_setviewport 688

Descrlpllan Creates a viewport.

#include <graph.h>

void _far _setviewport( short xl, short yl, short x2, short y2 );

xl , yl Upper-left comer of viewport

x2, y2 Lower-right corner of viewport

Remarks The _setviewport function redefines the graphics viewport. The _setviewport function
defines a clipping region in exactly the same manner as _setcliprgn, and then sets the
view-coordinate origin to the upper-left comer of the region. The physical points (xl, yl)
and (x2, y2) are the diagonally opposed corners of the rectangular clipping region. Any
window transformation done with the _setwindow function applies only to the viewport
and not to the entire screen.

Return Value None.

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

See Also _setcliprgn, _setvieworg, _setwindow

I * S V I EW P RT . C : T h i s p r o g r a m s e t s a v i ewpo r t a n d t h e n d r aws a recta n g l e


* a ro u n d i t a nd a n e l l i p s e i n i t .
*I

#i n c l u d e < c on i o . h >
#i n c l u d e < s t d l i b . h>
#i n c l u d e < g r a p h . h >

v o i d ma i n ( )
(
/ * Fi nd a v a l i d g ra p h i c s mod e . * /
i f ( ! _s e t v i deomod e ( _MAX RESMODE )
exi t ( 1 ) ;

_s e t v i ewp ort ( 100 , 100 , 200 , 200 ) ;


_re c t a n g l e ( _GBO RD E R , 0 , 0 , 100 , 100 ) ;
_e l l i p s e ( _G F I L L I NT E R I O R , 1 0 , 1 0 , 90 , 90 ) ;
689 _setviewpart

get c h C l ;
_s e t v i deomod e C _ D E FAU LTM O D E l ;
_setvisua/page 690

Description Sets the visual page.

#include <graph.h>

short _far _setvisualpage( short page );

page Visual page number

Remarks For hardware configurations that have an EGA or a VGA and enough memory to support
multiple-screen pages, the _setvisualpage function selects the current visual page. The
page argument specifies the current visual page. The default page number is 0.

Return Value The function returns the number of the previous visual page. If the function fails, it returns
a negative value.

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

See Also _getactivepage, _getvisualpage, _setactivepage, _setvideomode

Example See the example for _setactivepage.


691 _setwindow

Description Defines a graphics window.

#include <graph.h>

short _far _setwindow( shortfinvert, double wxl, double wyl, double wx2,
double wy2 );

finvert Invert flag

wxl , wyl Upper-left comer of window


wx2, wy2 Lower-right corner of window

Remarks The _setwindow function defines a window bounded by the specified coordinates. The
arguments (wxl, wyl) specify the upper-left comer of the window, and the arguments
(wx2, wy2) specify the lower-right comer of the window.
The finvert argument specifies the direction of the coordinates. lfjinvert is TRUE, the
y axis increases from the screen bottom to the screen top (Cartesian coordinates). If
finvert is FALSE, the y axis increases from the screen top to the screen bottom (screen
coordinates).

Any window transformation done with the _setwindow function applies only to the view­
port and not to the entire screen.

lf wxl equals wx2 or wyl equals wy2, the function will fail.

Note that this function does not affect the output of presentation-graphics text (e.g., labels,
axis marks, etc.). It also does not affect the output of the font display routine _outgtext.

Return Value The function returns a nonzero value if successful. If the function fails (e.g., if it is not in a
graphics mode), it returns 0.

Compal/bl//ty D ANSI • DOS D OS/2 D UNIX D XENIX

See Also _setviewport

/ * SW I N DOW . C : T h i s p r o g r a m i l l u s t ra t es t r a n s l a t i on between wi ndow ,


* v i ew , a nd p hy s i c a l c o o rd i n a t e s . Funct i on s u s ed i n c l u d e :
* _s etw i ndow _g etw i n d owcoo rd
* _g et p h y s c o o rd _g et v i ewc oo rd_wxy
*I
_setwindow 692

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


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

e n um boo l e a n ( FA L S E , T R U E l :
enum d i s p l ay ( MOV E , D RAW , E RA S E l :

v o i d ma i n ( )
(
s t ru c t xy coord v i ew , phys ;
s t r u c t _wxy coord o l dwi n , newwi n ;
s t r u c t v i d e o c on f i g v c :
d o u b l e x u n i t , y u n i t , x i nc , y i n c :
s h ort c o l o r , k ey , f i n t e r s e c t = FA LS E , fd i s p l ay = T RU E ;

I * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i deomod e C _MA X R E SM O D E ) l
exi t ( 1 ) :
_g et v i d eo c o n f i g ( & v c ) ;

I * Set a w i n d ow u s i n g rea l n umbe r s . * /


_s etw i ndow C FA LS E , - 1 2 5 . 0 , - 1 00 . 0 , 1 2 5 . 0 , 1 00 . 0 ) ;

I * C a l c u l a t e t h e s i ze of o n e p i x e l i n wi n d ow coord i n a t e s .
* T h e n get t h e c u r r ent w i ndow c o o rd i n a t e s a n d c o l o r .
*/
o l dwi n = _g etwi n d owcoord C 1 , 1 > :
n eww i n = _g etw i n d owcoord ( 2 , 2 > :
x u n i t = x i n c = n eww i n . wx - o l dwi n . wx :
yuni t • y i n c = n ewwi n . wy - o l dwi n . wy ;
n eww i n = o l dwi n = _g e t c u r re n t po s i t i on_w ( ) ;
c o l o r = _g e t c o l o r C > :

whi l e ( 1 )
(
/ * Set f l a g a c c o rd i n g to w h e t h e r c u r r e n t pi xel i s on , t h en
* t u rn p i x e l on .
*/
i f ( _g et p i x e l _w c o l dwi n . wx , o l dwi n . wy ) == c o l o r )
fi n t e r s e c t = T RU E :
el s e
f i n t e r s e c t = FALS E :
_s e t c o l o r C c o l o r > :
_s etp i x e l _w ( o l dwi n . wx , o l dwi n . wy > :
Bsa _setwindaw

I * Get a n d t e s t key . * /
k ey = getc h ( ) ;
swi tc h ( k ey >
(
case 27 : / * ESC Q u i t */
_s et v i d eomod e ( _D E FAU LTMOD E ) ;
exi t ( 0 > :
case 32 : / * S PAC E Move no col or */
fd i s p l a y = MO V E ;
cont i nue ;
case 0 : / * E x t e n d ed c o d e - get next * /
k ey = get c h ( > :
swi t c h ( key )
(
case 72 : I* U P -y *I
n eww i n . wy -= y i nc ;
b r ea k ;
case 77 : I * R I GHT +x *I
n ewwi n . wx += x i n c ;
b r ea k ;
c a s e 80 : I * DOWN +y *I
n eww i n . wy += y i n c ;
b rea k :
case 75: I * L E FT -x *I
n eww i n . wx - = x i n c ;
b r ea k ;
c a s e 82 : I* INS D r a w whi te *I
fdi s p l a y = D RAW ;
con t i n u e ;
c a s e 83 : I* DEL D r a w bl a c k *I
fdi s p l ay = E RAS E ;
con t i n u e ;

brea k ;

I * T r a n s l a t e wi ndow c o o rd i n a t e s t o v i ew , v i ew t o p hy s i c a l .
* T h e n c h e c k p hy s i c a l to ma k e s u re we ' re on s c reen . U p d a t e s c reen
* a nd po s i t i on i f we a r e . I gn o r e if not .
*I
v i ew = _g e t v i ewc oo rd_wxy ( &n ewwi n ) ;
phys = _g e t p hy s c o o rd ( v i ew . x c o o rd , v i ew . y c o o rd > :
i f ( C p hys . x c o o rd >= 0 ) && C p hys . xcoord < v c . n umx p i x e l s ) &&
C p hys . y coo rd >= 0 ) && C p hys . ycoord < v c . n umy p i x e l s ) )
_setwindow 694

I * I f d i s p l a y o n , d ra w t o n ew po s i t i on , e l s e move t o new . * /
i f ( f d i s p l a y ! = MOV E )
(
i f ( f d i s p l a y � E RA S E )
_s e t c o l o r C 0 ) ;
_l i n e t o_w c n ewwi n . wx , n ewwi n . wy ) ;

el se
{
_s e t c o l o r ( 0 ) ;
_mo v e t o_w C n eww i n . wx , n eww i n . wy ) ;

I * I f t h e r e w a s n o i nt e r s e c t , e ra s e ol d p i x e l . * /
i f C ! f i n t e r s ect )
_s e t p i x e l _w C o l dwi n . wx , o l dwi n . wy ) ;
)
o l dwi n = n eww i n ;
)
el se
n eww i n = o l dwi n ;
695 _setwritemode

Description Sets the current logical mode for line drawing.

#include <graph.h>

short _far _setwritemode( short action );

action Interaction with existing screen image

Remarks The _setwritemode function sets the current logical write mode, which is used when draw­
ing lines with the _lineto and _rectangle functions.

The action argument defines the write mode. The possible values are _GAND, _GOR,
_GPRESET, GPSET, and _GXOR. See the description of the _putimage function for
_

more details on these manifest constants.

Return Value The _setwritemode function returns the previous write mode, or -1 if an error occurs.

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

See Also _getwritemode, _grstatus, _lineto functions, _putimage functions, _rectangle


functions, _setcolor, _setlinestyle

Example See the example for _getwritemode.


signal 696

Dacr/pllon Sets interrupt signal handling.

#include <Signal.h>

void ( *signal( int sig, void( *June )( int sig [, int subcode ] ) ) ) ( int sig );

sig Signal value

June Function to be executed

subcode Optional subcode to the signal number

Remarks The signal function allows a process to choose one of several ways to handle an interrupt
signal from the operating system.

The sig argument must be one of the manifest constants described in Table R. 1 1 and de­
fined in SIGNAL.ff.

Table R.11 Signals and Responses

Value Modes Meaning Default Action

SIGABRT Real, Abnonnal tennination Tenninates the calling program


protected with exit code 3
SIGBREAK Protected CTRL+BREAK signal Tenninates the calling program
with exit code 3
SIGFPE Real, Floating-point error Tenninates the calling program
protected with exit code 3
SIGILL Real, Illegal instruction Tenninates the calling program
protected with exit code 3
SIGINT Real, CTRL+C signal Tenninates the calling program
protected with exit code 3
SIGSEGV Real, Illegal storage access Tenninates the calling program
protected with exit code 3
SIGTERM Real, Termination request Tenninates the calling program
protected with exit code 3
SIGUSRl Protected OS/2 process flag A Signal is ignored
SIGUSR2 Protected OS/2 process flag B Signal is ignored
SIGUSRJ Protected OS/2 process flag C Signal is ignored

SIGUSRl, SIGUSR2, and SIGUSRJ are user-defined signals which can be sent by means of•
DosFlagProcess. For details, see Microsoft Operating System/2 Programmer's Reference.
697 signal

Note that SIGILL, SIGSEGV, and SIGTERM are not generated under DOS and SIGSEGV
is not generated under OS/2. They are included for ANSI compatibility. Thus, you may set
signal handlers for these signals via signal, and you may also explicitly generate these sig­
nals by calling raise.

Note also that signal settings are not preserved in child processes created by calls to exec
or spawn. The signal settings are reset to the default in the child process.

The action taken when the interrupt signal is received depends on the value ofjunc. The
June argument must be either a function address or one of the manifest constants defined in
SIGNAL.ff and listed below:

Value Meaning
SIG_ACK Acknowledges receipt of a signal (OS/2 only). This constant
is valid only if a user-defined signal handler is installed. Once
a process receives a given signal, the operating system does
not send any more signals of this type until it receives a
SIG_ACK acknowledgment from the process. The operating
system does not queue up signals of a given type; therefore, if
more than one signal of a given type accumulates before the
process returns a SIG_ACK value, only the most recent signal
is sent to the process after the SIG_ACK value is received by
the operating system. This option has no effect on which han­
dler is installed for a given signal. The manifest constant
SIG_ACK is not supported for SIGFPE signals.

SIG_DFL Uses system-default response. The system-default response


for all signals except SIGUSRl, SIGUSR2, and SIGUSR3 is to
abort the calling program. The calling process is terminated
with exit code 3, and control returns to DOS or OS/2. If the
calling program uses stream 1/0, buffers created by the run­
time library are not flushed, but buffers created by the operat­
ing system are flushed. The default response for SIGUSRl,
SIGUSR2, and SIGUSR3 is to ignore the signal.

SIG_ERR Ignores interrupt signal (OS/2 only). This constant is equiv­


alent to SIG_IGN, except that any process that tries to send
this signal receives an error. A process may use the raise func­
tion to send a signal to itself. A different process may send a
signal by means of the function DosFlagProcess (if the signal
is SIGUSRl, SIGUSR2, or SIGUSR3) or by means of
DosKillProcess (if the signal is SIGTERM) .
SIG_IGN Ignores interrupt signal. This value should never be given for
SIGFPE, since the floating-point state of the process is left
undefined.
signal 698

Function address Installs the specified function as the handler for the given
signal.

For all signals except SIGFPE and SIGUSRX, the function is


passed the sig argument SIGINT and executed.

For SIGFPE signals, the function is passed two arguments;


namely SIGFPE and the floating-point error code identifying
the type of exception that occurred.

For SIGUSRl, SIGUSR2, and SIGUSR3, the function is passed


two arguments: the signal number and the argument furnished
by the DosFlagProcess function.

For SIGFPE, the function pointed to by June is passed two arguments, SIGFPE and an
integer error subcode, FPE_xu; then the function is executed. (See the include file
FLOAT.ff for definitions of the FPE_xu subcodes.) The value ofJune is not reset upon re­
ceiving the signal. To recover from floating-point exceptions, use setjmp in conjunction
with longimp. (See the example under _fpreset.) If the function returns, the calling
process resumes execution with the floating-point state of the process left undefined.

If the function returns, the calling process resumes execution immediately following the
point at which it received the interrupt signal. This is true regardless of the type of signal
or operating mode.

Before the specified function is executed under DOS versions 3.x or earlier, the value
ofjunc is set to SIG_DFL. The next interrupt signal is treated as described above for
SIG_DFL, unless an intervening call to signal specifies otherwise. This allows the program
to reset signals in the called function.

Under OS/2, the signal handler is not reset to the system-default response. Instead, no sig­
nals of a given type are received by a process until the process sends a SIG_ACK value to
the operating system. The program can restore the system-default response from the han­
dler by first sending SIG_DFL and then sending SIG_ACK to the operating system.

Since signal-handler routines are normally called asynchronously when an interrupt oc­
curs, it is possible that your signal-handler function will get control when a C run-time
operation is incomplete and in an unknown state. Certain restrictions therefore apply to the
C functions that can be used in your signal-handler routine:

1 . Do not issue low-level or standard input and output routines (e.g., printf, read, write,
and fread) .

2. Do not call heap routines or any routine that uses the heap routines (e.g., malloc,
strdup, putenv).
3. Do not use any C function that generates a system call (e.g., getcwd, time).
699 signal

4. Do not use the longjmp function unless the interrupt is caused by a floating-point ex­
ception (i.e., sig is SIGFPE). In this case, the program should first reinitialize the
floating-point package by means of a call to _fpreset.

5. Do not use any overlay routines.

Return Value The signal function returns the previous value offunc associated with the given signal. For
example, if the previous value offunc was SIG_IGN, the return value will be SIG_IGN.
The one exception to this rule is SIG_ACK, which returns the address of the currently in­
stalled handler.

A return value of -1 indicates an error, and ermo is set to EINVAL. The possible error
causes are an invalid sig value, an invalidfunc value (that is, a value that is less than
SIG_ACK but not defined), or afunc value of SIG_ACK used when no handler is currently
installed.

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

See Also abort, exec functions, exit, _exit, _fpreset, spawn functions

I * S I GN A L . C i l l u s t ra t e s s e t t i ng u p s i g n a l i n t e r r upt rout i n e s . Fun c t i o n s


* i l l u s t ra t ed i n c l ude s i g n a l a n d r a i s e .
*
* S i n c e C I / O f u n c t i o n s a re not s a fe i n s i d e s i g n a l rou t i n e s , t h e code
* uses c o n d i t i o n a l s t o u s e sy s t em- l ev e l DOS a n d O S / 2 s e r v i c e s . An o t h e r
* opt i on i s t o s e t g l oba l fl a g s a n d d o a ny I / O o p e ra t i o n s o u t s i d e t h e
* s i g n a l h a n d l e r . T o c omp i l e t h e O S / 2 v e r s i on , d e f i n e t h e symbol OS2 .
*I

#i n c l u d e < s t d i o . h >
Iii n c l u d e < c on i o . h >
#i n c l u d e < s i g n a l . h >
#i n c l u d e < p r o c e s s . h >
#i n c l u d e < s t d l i b . h >
#i f d ef i ned ( OS2 )
#d e f i ne I N C L_NOCOMMON
#d e f i ne I N C L_NO P M
#d e f i n e I N C L_V I O
#d e f i ne I N C L_KBD
/Fi n c l u d e < o s 2 . h >
#i n c l u d e < s t r i n g . h >
Itel s e
/Fi n c l u d e < d o s . h >
#i n c l ude < b i o s . h >
lfoen d i f
signal 700

voi d ctrl chandl er< voi d > ; I * P rototypes * /


v o i d s a feout ( c h a r * s t r } ;
i nt sa fei n ( voi d > ;

v o i d ma i n ( }
(
i nt c h ;

I * M o d i fy CTRL+C b e ha v i o r . * /
i f ( s i g n a l ( S I G I NT , c t r l c h a n d l e r }
= S I G_ERR }
(
fp r i n t f ( s t d e r r , " C oul d n ' t s e t S I G I NT \ n " } ;
a b o rt ( } ;

I * I n p u t l oop i l l u s t r a t e s r e s u l t s . * /
do
(
c h = getch C } ;
i f ( c h == 0 >
(
c h = getc h C } ;
i f ( c h == 4 6 } / * T r e a t A LT+C l i k e C T R L+C * /
r a i s e c S I G I NT } ;
el se
p r i n t f ( " Ex t e n ded c o d e : % X \ n " , c h } ;

el se
p r i n t f ( " A SC I I code : % X \ n " , c h } ;
whi l e ( c h ! = 27 } ; / * ESC c o d e * I

I * H a n d l e s S I G I NT C CT R L+C } i n t e r r upt . * /
voi d ctrl chandl er( }
(
i nt c ;
char str[J = • " ;

I * D i s a l l ow CTRL+C d u r i ng h a n d l e r . * /
s i g n a l ( S I G I NT , S I G_I G N } ;

s a feout ( " U s e r b r e a k - a bo r t p r o c es s i n g ? • } ;
c = s a fe i n ( } ;
str[0J = c :
s a feout < s t r } ;

i f ( ( C = ' y ' } 1 1 ( C == ' Y ' } }


s a feout ( " \ r \ n " } ;

a bo rt ( } ;
el se
101 signal

I * T h e C T R L+C i n t e r rupt mu s t be reset t o o u r h a nd l e r s i n c e


* b y d e fa u l t i t i s reset t o t h e s y s t em h a n d l e r .
*I
s i g na l ( S I G I NT , c t r l c h a n d l e r ) ;

I * O u t p u t s a s t r i n g u s i n g s y s t em l ev e l c a l l s . * /
v o i d s a feou t C c h a r * s t r )
{
#i f d e f i ned ( OS2 )
V i oWrtTTY C s t r , s t r l en C s t r ) , 0 ) ;
I/e l s e
u n i on REGS i n regs , o u t regs ;

i n regs . h . a h = 0x0e ;
whi 1 e C *str )
{
i n re g s . h . a l = * s t r++ ;
i n t86 C 0 x l 0 , & i n re g s , & o u t r e g s ) ;
)
llen d i f
)

I * I n p u t s a c h a r a c t e r u s i n g s y s t em l ev e l c a l l s . * /
i nt s a f e i n ( )
{
#i f d ef i ned ( OS2 )
K B D K E Y I N FO k k i ;

Kbd C h a r i n C & k k i , I O_WA I T , 0 ) ;


return kki . ch C ha r :
I/el s e
r e t u r n _b i os_keybrd C _KE Y B RD_READ ) & 0xff ;
l/en d i f
)

Output

ASC I I code : 7 4
ASC I I c o d e : 68
ASC I I code : 65
"C
U s e r b rea k - a bo r t p r o c e s s i n g ? n

18
ASC I I code : 6 2
ASC I I code :
sin Functions 702

Description Calculate sines and hyperbolic sines.

#include <math.h>

double sin( double x ) ;


double sinh( double x ) ;
long double sinl( long double x ) ;
long double sinhl( long double x ) ;

x Angle in radians

Rematks The sin and sinh functions find the sine and hyperbolic sine of x, respectively. The sinl
and sinhl functions are the 80-bit counterparts and use 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 sin functions return the sine of x. If x is large, a partial loss of significance in the result
may occur, and sin generates a PLOSS error. If x is so large that significance is completely
lost, the sin function prints a TLOSS message to stderr and returns 0. In both cases, errno
is set to ERANGE.

The sinh function returns the hyperbolic sine of x. If the result is too large, sinh sets ermo
to ERANGE and returns ±HUGE_VAL.

Campallbll/ly sin, sinh

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

sin1, sinhl

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

See Also ac� functions, asin functions, atan functions, cos functions, tan functions

I * S I N C O S . C : T h i s p r o g r a m d i s p l ay s t h e s i n e , hy p erbol i c s i n e , c o s i n e ,
* a nd hy p e r b o l i c c o s i n e of p i I 2 .
*I
703 sin Functions

#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 pi = 3 . 1 4 1 5 9 2 6 5 3 5 ;
doubl e x , y ;

x = pi I 2 ;
y = si n ( x > :
p r i n t f ( " s i n ( %f ) = % f \ n " , x , y >:
y = sinhC x > :
p r i n t f ( " s i n h ( %f ) = % f \ n " , x , y >:
Y = C OS ( X ) ;
p r i n t f C " c o s ( %f > = % f \ n " , x , y >:
y = c os h C x > :
p r i n t f ( " c os h ( %f ) = %f\ n " , x , y >:

Output

s i n ( 1 . 570796 ) =1 . 000000
s i nh ( 1 . 570796 ) =2 . 30 1 2 9 9
C O S ( 1 . 5 7 0 7 9 6 ) = 0 . 000000
c os h ( 1 . 5 7 0 7 9 6 > = 2 . 509 1 7 8
sopen 704

Descr/plion Opens a file for file sharing.

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

int sopen( char *filename, int oflag, int shflag [, int pmode D );

filename File name

oflag 'fype of operations allowed

shf/ag 'fype of sharing allowed

pmode Pennission setting

Remarks The sopen function opens the file specified by filename and prepares the file for sub­
sequent shared reading or writing, as defined by oflag and shflag. The integer expression
oflag is fonned by combining one or more of the following manifest constants, defined in
the file FCNTL.H. When two or more constants are used to fonn the argument oflag, the
constants are combined with the OR operator ( I ).

Constant Meaning

O_APPEND Repositions the file pointer to the end of the file before every
write operation.
O_BINARY Opens file in binary (untranslated) mode. (See fopen for a de­
scription of binary mode.)
O_CREAT Creates and opens a new file. This has no effect if the file
specified by filename exists.
O_EXCL Returns an error v alue if the file specified by filename exists.
This applies only when used with O_CREAT.
O_RDONLY Opens file for reading only. If this flag is given, neither the
O_RDWR flag nor the O_WRONLY flag can be given.

O_RDWR Opens file for both reading and writing. If this flag is given,
neither 0_RDONLY nor O_WRONLY can be given.
705 sopen

O_TEXT Opens file in text (translated) mode. (See fopen for a descrip­
tion of text mode.)
O_TRUNC Opens and truncates an existing file to 0 bytes. The file must
have write pennission; the contents of the file are destroyed.
O_WRONLY Opens file for writing only. If this flag is given, neither
0_RDONLY nor 0_RDWR can be given.
The argument shflag is a constant expression consisting of one of the following manifest
constants, defined in SHARE.ff. 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 infonnation about sharing modes.)

Constant Meaning

SH_COMPAT Sets compatibility mode (not available in OS/2). This is the


sharing mode used in the open function in DOS.
SH_DENYRW Denies read and write access to file.
SH_DENYWR Denies write access to file.
SH_DENYRD Denies read access to file.
SH_DENYNO Pennits read and write access. This is the sharing mode used
in the open function in OS/2.

The sopen function should be used only under OS/2 and DOS versions 3.0 and later.
Under earlier versions of DOS, the shflag argument is ignored.

The pmode argument is required only when o_CREAT is specified. If the file does not
exist, pmode specifies the file's pennission settings, which are set when the new file is
closed for the first time. Otherwise, the pmode argument is ignored. The pmode argument
is an integer expression that contains one or both of the manifest constants S_IWRITE and
S_IREAD, defined in SYS\STAT.H. When both constants are given, they are combined
with the OR operator ( I ). The meaning of the pmode argument is as follows:

Value Meaning

S_IWRITE Writing pennitted


S_IREAD Reading pennitted
s_IREAD 1 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.
sopen 706

Note that under DOS versions 3.x with SHARE installed, a problem occurs when opening
a new file with sopen under the following sets of conditions:

• Witli oflag set to O_CREAT I O_RDONLY or o_CREAT I WRONLY, pmode set to


S_IREAD, and shflag set to SH_COMPAT.

• With oflag set to any combination that includes O_CREAT I O_RDWR, pmode set to
S_IREAD, and shflag set to anything other than SH_COMPAT.

In either case, the operating system will prematurely close the file during system calls
made within sopen, or the system will generate a sharing violation (INT 24H). To avoid
the problem, open the file with pmode set to S_IWRITE. After closing the file, call chmod

set to S_IREAD, oflag set to O_CREAT I O_RDWR, and shflag set to SH_COMPAT.
and change the mode back to S_IREAD. Another solution is to open the file with pmode

permissions (see umask).


The sopen function applies the current file-permission mask to pmode before setting the

Retum Value The sopen function returns a file handle for the opened file. A return value of -1 indicates
an error, and errno is set to one of the following values:

Value Meaning

EACCES Given path name is a directory; or the file is read-only but an


open for writing was attempted; or a sharing violation oc­
curred (the file's sharing mode does not allow the specified
operations; OS/2 and DOS versions 3.0 and later only).

EEXIST The o_CREAT and o_EXCL flags are specified, but the
named file already exists.

EINVAL An invalid oflag or shflag argument was given.

EMFILE No more file handles available (too many open files).

ENOENT File or path name not found.

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

See Also close, creat, fopen, _fsopen, open, umask

Example See the example for locking.


707 spawn Functions

DBScrlptlon Create and execute a new child process.

#include <Stdio.h>
#include <process.h>

int spawnl( int mode, char *cmdname, char •argO, char *argl, ... char •argn, NULL );
int spawnle( int mode, char *cmdname, char *argO, char *argl , ... char *argn, NULL,
char **envp ) ;
int spawnlp( int mode, char *cmdname, char *argO, char *argl, ... char *argn, NULL );
int spawnlpe( int mode, char *cmdname, char *argO, char *argl, ... char *argn, NULL,
char **envp );
. int spawnv( int mode, char *cmdname, char **argv );
int spawnve( int mode, char *cmdname, char **argv, char **envp ) ;
int spawnvp( int mode, char *cmdname, char **argv );
int spawnvpe( int mode, char *cmdname, char **argv, char **envp );

mode Execution mode for parent process

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

Remalks The spawn family of functions creates and executes a new child process. Enough memory
must be available for loading and executing the child process. The mode argument deter­
mines the action taken by the parent process before and during spawn. The following
values for mode are defined in PROCESS.ff:

Value Meaning

P_DETACH Continues to execute the parent process; child process is run


in the background with no access to the console or keyboanl.
Calls to wait and cwait against the child process will fail.
This is an asynchronous detached spawn and is valid only in
OS{}. protected mode.
spawn Functions 708

P_NOWAIT Continues to execute parent process concurrently with child


process (asynchronous spawn, valid only in protected mode).

P_NOWAITO Continues to execute parent process and ignores wait and


cwait calls against child process (asynchronous spawn, valid
only in protected mode).

P_OVERLAY Overlays parent process with child, destroying the parent


(same effect as exec calls).

P_WAIT Suspends parent process until execution of child process is


complete (synchronous spawn).

The cmdname argument specifies the file which will be executed as the child process, and
can specify 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 (.), the spawn function first tries the .COM extension, then the .EXE extension, and
finally the .BAT extension (or, in OS/2 protected mode, the .CMD extension). This ability
to spawn batch files is a new feature in Microsoft C version 6.0.

If cmdname has an extension, only that extension is used. If cmdname ends with a period,
the spawn calls search for cmdname with no extension. The spawnlp, spawnlpe,
spawnvp, and spawnvpe 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
spawn call searches only for the specified file and no path searching is done.

Arguments for the Child Process

Arguments are passed to the child process by giving one or more pointers to character
strings as arguments in the spawn call. These character strings form the argument list for
the child process. The combined length of the strings forming the argument list for the
child process must not exceed 128 bytes in real mode. The terminating null character ( '\0 ' )
for each string is not included in the count, but space characters (automatically inserted to
separate arguments) are included.

The argument pointers may be passed as separate arguments (spawnl, spawnle. spawnlp,
and spawnlpe) or a8 an array of pointers (spawnv, spawnve, spawnvp, and spawnvpe).
At least one argument, argO or argv[O], must be passed to the child process. By conven­
tion, this argument is the name of the program as it might be typed on the command line
by the user. (A different value will not produce an error.) In real mode, the argv[O] value is
supplied by the operating system and is the fully qualified path name of the executing pro­
gram . In protected mode, it is usually the program name as it would be typed on the com­
mand line.
709 spawn Functions

The spawnl. spawnle. spawnlp, and spawnlpe calls are typically used in cases where the
number of arguments is known in advance. The argO argument is usually a pointer to
cmdname. The arguments argl through argn are pointers to the character strings forming
the new argument list. Following argn, there must be a NULL pointer to mark the end of
the argument list.

The spawnv. spawnve. spawnvp, and spawnvpe calls are useful when the number of ar­
guments to the child process is variable. Pointers to the arguments are passed as an array.
argv. The argument argv[O] is usually a pointer to a path name in real mode or to the pro­
gram name in protected mode, and argv[ I ] through argv[n] are pointers to the character
strings forming the new argument list. The argument argv[n+l] must be a NULL pointer to
mark the end of the argument list.

Environment of the Child Process

Files that are open when a spawn call is made remain open in the child process. In the
spawnl, spawnlp, spawnv. and spawnvp calls, the child process inherits the environment
of the parent. The spawnle. spawnlpe, spawnve, and spawnvpe 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 ele­
ment of which (except for the final element) points to a null-terminated string defining an
environment variable. Such a string usually has the form

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.

The spawn functions can pass the child process all information about open files, including
the translation mode, through the C_FILE_INFO entry in the environment that is passed in
real mode (_C_FILE_INFO in protected mode).
The C start-up code normally processes this entry and then deletes it from the environ­
ment. However. if a spawn function spawns a non-C process (such as CMD.EXE). this
entry remains in the environment. Printing the environment shows graphics characters in
the definition string for this entry, since the environment information is passed in binary
form in real mode. It should not have any other effect on normal operations. In protected
mode, the environment information is passed in text form and therefore contains no
graphics characters.

You must explicitly flush (using mush or flushall) or close any stream prior to the spawn
function call.
spawn Functions 710

Starting with Microsoft C version 6.0, you can control whether or not the open file infor­
mation of a process will be passed to its child processes. The external variable _fileinfo
(declared in STDLIB.H) controls the passing of C_FILE_INFO information. If _fileinfo is
0, the C_FILE_INFO information is not passed to the child processes. If _rdeinfo is not 0,
C_FILE_INFO is passed to child processes.

B y default, _fileinfo is 0 and thus the C_FILE_INFO information is not passed to child
processes. There are two ways to modify the default value of _fileinfo:

• Link the supplied object file FILEINFO.OBJ into your program. Use the /NOE option
to avoid multiple symbol definitions.

• Set the _fileinfo variable to a nonzero value directly within your C program.

Retum Value The return value from a synchronous spawn (P_wAIT specified for mode) is the exit sta­
tus of the child process. -

The return value from an asynchronous spawn (P_NOWAIT or P_NOWAITO specified for
mode) is the process ID. To obtain the exit code for a process spawned with P_NOWAIT,
you must call the wait or cwait function and specify the process ID. The exit code cannot
be obtained for'a process spawned with P_NOWAITO.

The exit status is 0 if the process terminated normally. The exit status can be set to a non­
zero value if the child process specifically calls the exit routine with a nonzero argument.
If the child process did not explicitly set a positive exit status, a positive exit status indi­
cates an abnormal exit with an abort or an interrupt. A return value of -1 indicates an
error (the child process is not started). In this case, errno is set to one of the following
values:

Value Meaning

E2BIG In DOS, the argument list exceeds 128 bytes, or the space
required for the environment information exceeds 32K. In
OS/2, the argument list and the space required for environ­
ment information combined exceed 32K.

EINVAL The mode argument is invalid.

ENOENT The file or path name is 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.

Note that signal settings are not preserved in child processes created by calls to spawn
routines. The signal settings are reset to the default in the child process.
71 1 spawn Functions

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

The spawn functions, with P_OVERLAY mode, will not work in OS/2 DOS­
compatibility mode in programs which are bound with FAPI for dual-mode execution.

Programs linked as DOS mode .EXE files will work, and protected-mode programs will
work. The restriction applies only to bound programs in real mode.

In order to ensure proper overlay initialization and termination, do not use the setjmp or
longimp functions to enter or leave an overlay routine.

Su A/10 abort, atexit, exec functions, exit, _exit, onexit, system

I * S PAWN . C : T h i s p r o g r a m a c c e p t s a number i n t h e r a n g e 1 - 8 from t h e


* c omma nd l i ne . B a s ed on t h e number i t rec e i v e s , i t executes o n e o f t h e
* e i g h t d i fferent 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 . F o r
* s ome of t h e s e p roced u r e s , t h e C H I LD . E X E f i l e mu s t be i n t h e
* s a me d i r e c t o ry ; f o r o t h e r s , i t o n l y h a s t o be i n t h e s a me pa t h .
*I

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

c ha r *my_e n v [ ] =
(
" TH I S=en v i ronment w i l l b e " ,
" PASS ED=to c h i l d . ex e by t h e " ,
" S PAWN L E=a nd " ,
" S PAWN L P E=a nd " ,
" S PAWNV E=a nd " ,
" S PAWN V P Eafu n c t i on s " ,
NULL
};

v o i d ma i n ( i n t a rgc , c h a r * a rgv [ ] l
{
c h a r *a r g s [ 4 ] ;
i nt resul t ;

' / * Set u p p a ramet e r s t o be s ent : * /


a rg s ( 0 ]= "chi ld" ;
a rg s [ l ] = " s pawn ? ? " ;
a rg s [ 2 ] = " two " ;
a rg s [ 3 ] = N U L L ;
s w i t c h C a rg v [ 1 ] [ 0 ] ) / * B a s ed on f i rst l et t e r of a rg ument * /
(
case ' l ' :
spawn Functions 712

s p a wn l ( P_WA I T , a rg v [ 2 ] , a rg v [ 2 ] , " s pawnl " , " two " , N U L L ) ;


b r ea k ;
case ' 2 ' :
s p a wn l e C P_WA I T , a rg v [ 2 ] , a rg v [ 2 ] , " s pawnl e " , " two " ,
N U L L , my_e n v > :
brea k ;
case ' 3 ' :
s p a wn l p C P_WA I T , a rg v [ 2 ] , a rgv [ 2 ] , " s pa w n l p " , " two " , N U L L > :
b r ea k ;
case ' 4 ' :
s p a wn l p e C P_WA I T , a rg v [ 2 ] , a rg v [ 2 ] , " s pawnl p e " , " two " ,
N U L L , my_en v ) ;
b rea k ;
case ' 5 ' :
s p a wn v C P_O V E R LAY , a rg v [ 2 ] , a rg s > :
brea k ;
case ' 6 ' :
s p a w n v e C P_O V E R LAY , a rg v [ 2 ] , a rg s , my_env > :
b r ea k ;
case ' 7 ' :
s p a wn v p C P_O V E R LAY , a rg v [ 2 ] , a rg s > :
b r ea k ;
case ' 8 ' :
s pa w n v pe C P_O V E R LAY , a r g v [ 2 ] , a r g s , my_env > :
brea k ;
defa u l t :
p r i n t f ( " SY NTAX : SPAWN < 1 - 8> <c h i l d p ro g r a m> \ n " ) ;
ex i t C 1 > :
I
p r i n t f C " \ n \ n Retu rned f rom S PAWN ! \ n " > :
713 _splitpath

Dest:tlptlon Breaks a path name into components.

#include <Stdlib.h>

void _splitpath( char *path, char *drive, char *dir, char *fname, char *ext );

path Full path name

drive Drive letter


dir Directory path

fname File name


ext File extension

Rematltl The _splitpath routine breaks a full path name into its four components. The path argu­
ment should point to a buffer containing the complete path name. The maximum size nec­
essary for each buffer is specified by the manifest constants _MAX_DRIVE, _MAX_DIR,
_MAX_FNAME, and _MAX_EXT, defined in STDLIB.H. The other arguments point to the
buffers used to store the path-name elements:

Buff'er Description
drive Contains the drive letter followed by a colon (:) if a drive is
specified in path.

dir Contains the path of subdirectories, if any, including the trail­


ing slash. Forward slashes ( I ) , backslashes ( \ ) , or both may
be present in path.

fname Contains the base file name without any extensions.

ext Contains the file-name extension, if any, including the leading


period (.).

The return parameters will contain empty strings for any path-name components not found
in path.

Retum Value None.

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


_splitpath 114

S11 A/11a _ fullpath, _makepath

Exampm ��������--

1 * MAK E PATH . C * /
#i n c l u d e < 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 p a t h_buffer [_MAX_PAT H J ;
c h a r d r i v e [_MAX_D R I V E J ;
c h a r d i r [_MAX_D I R] ;
c h a r fname [_MAX_FNAM E J ;
c h a r ext [_MAX_E X T ] ;

_ma kepa t h ( p a t h_b uff�r . • c • , " \ \ c 60\ \ c l i b r e f \ \ " , • ma kepa t h " , • c • > :
p r i nt f ( " P a t h c re a ted wi t h _ma kepa t h : %s \ n \ n " , p a t h_buffer > :
_s p l i tp a t h ( p a t h_buffe r , d r i v e , d i r , f n a me , ext > :
p r i n t f ( " Pa t h ext r a c t ed w i t h _s p l i t p a t h : \ n " ) ;
pri ntf ( • Dri v e : %s\n " , dri ve ) ;
pri ntf ( • Di r : % s \n " , di r > :
p r i n t f ( • Fi l e n a me : % s \ n " , f n a me > :
p r i n t f ( • Ext : % s \ n " , ext > :

Output

P a t h c r e a t ed w i t h _ma k e p a t h : c : \ c 6 0 \ c l i b ref\ma kepa t h . c

P a t h ext r a c t ed w i t h _s p l i tp a t h :
Dri ve : c :
D i r : \ c 60 \ c l i bref\
F i l e n a me : ma kepa t h
Ext : . c
715 sprinlf

Description Writes formatted data to a string.

#include <Stdio.h>

int sprintf( char *buffer, const char *format [, argument] ... );

buffer Storage location for output

format Format-control string

argument Optional arguments

Remarks The sprintf function formats and stores a series of characters and v alues in buffer. Each
argument (if any) is converted and output according to the corresponding format specifica­
tion in the format. The format consists of ordinary characters and has the same form and
function as the format argument for the printf function. (See printf for a description of the
format and arguments.) A null character is appended to the end of the characters written,
but is not counted in the return value.

Return Value The sprintf function returns the number of characters stored in buffer, not counting the
terminating null character.

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

See Also fprintf, printf, sscanf

I * S P R I NT F . C : T h i s p r o g r a m u s e s s p r i n t f to fo rma t v a r i o u s d a t a a n d
· * p l a c e t h em i n t h e s t r i n g n a med b u f fe r .
*I

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

v o i d ma i n ( )
(
c h a r b u f f e r [ 200 ] , s [ ] = • comp u t e r • , c = ' l ' :
i nt i = 35 , j :
f l o a t fp = 1 . 7 320534 :
sprintf 116

/ * Fo rma t a n d p r i n t v a r i ous d a t a : */
j = spri ntf ( buffe r , " \tStri ng : %s \ n " , s >:
j += s p r i n t f C buffer + j , " \tCha racter : %c \ n " , c l:
j += s p r i n t f ( buffer + j , " \t l ntege r : %d \ n R I i ):
j += s p r i n t f C buffe r + j , " \ t Rea l : %f\ n " , fp l :

p r i n t f C " Ou t p u t : \ n% s \ n c h a r a c t e r c o u n t = % d \ n " , buffe r , j > :

Output

O u t pu t :
St r i n g : c omp u t e r
Cha racter : l
I nt e g e r : 35
Rea l : 1 . 732053

cha racter count = 71


717 sqrt, sqrt/

DBBcrlptlon Calculates the square root.

#include <math.h>

double sqrt( double x );


long double sqrtl( long double x );

x Nonnegative floating-point value

Remalb The sqrt functions calculate the square root of x. The sqrtl function is the 80-bit counter­
part and uses an 80-bit, I 0-byte coprocessor fonn of arguments and return values.

Return Value The sqrt functions return the square-root result. If x is negative, the function prints a
DOMAIN error message to stderr, sets ermo to EDOM, and returns 0.
Error handling can be modified by using the matherr or _matherrl routine.

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

See Also exp, IQg, matherr, pow

Examp• --
---

/ * SO RT . C : T h i s p r o g r a m c a l c u l a t e s a s q u a re root . * /
#i n c l ude <ma t h . 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
d o u b l e q u es t i on = 4 5 . 3 5 , a n swe r :

a n sw e r = s q rt ( q u es t i on ) ;
i f ( e rr n o == EDOM >
p r i n t f ( " Doma i n e r ro r \ n " > :
el s e
p r i n t f ( " T h e s q u a re root o f % . 2 f i s % . 2 f\ n " , q u e s t i on , a n swer > :

Output

T h e s q u a re root o f 4 5 . 3 5 i s 6 . 7 3
srand 718

Description Sets a random starting point.

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

void srand( unsigned int seed );

seed Seed for random-number generation

Remarks The srand function sets the starting point for generating a series of pseudorandom in­
tegers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed
sets the generator to a random starting point.

The rand function is used to retrieve the pseudorandom numbers that are generated. Call­
ing rand before any call to srand will generate the same sequence as calling srand with
seed passed as 1 .

Return Value None.

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

See Also rand

Exampre __________________________________________________________________�

I * RAN D . C : T h i s p r o g r a m s e e d s t h e ra ndom n um b e r g e n e r a t o r w i t h t h e
* t i me , t h e n d i s p l a y s 20 r a n d om i n t e g e r s .
*I

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

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

/ * Seed t h e r a n d om number g en e r a t o r w i t h c u r r ent t i me s o t h a t


* t h e n umb e r s wi l l be d i f f e r e n t e v e ry t i me w e r u n .
*/
s ra n d ( ( un s i gned l t i me < NU L L ) ) ;
719 srand

I * D i s p l a y 10 numbe r s . * /
fo r < i � 0 ; i < 1 0 ; i ++ >
p r i ntf ( • %6d \ n " , r a nd ( ) > ;

Output

1947 1
16395
8268
1 5 582
6489
283 5 6
27042
5276
23070
10930
sscanf 720

Oaar/ptlon Reads formatted data from a string.

#include <Stdio.h>

int sscanf( const char *buffer, const char *format I[, argument :U ••• );

buffer Stored data

format Format-control string

argument Optional arguments

Remarks The sscanf function reads data from buffer into the locations given by each argument.
Every argument must be a pointer to a variable with a type that corresponds to a type speci­
fier in format. The format 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 complete
description offormat.

Return Value The sscanf 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-string. A return value of 0 means
that no fields were assigned.

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

See Also fscanf, scanf, sprintf

/ * SSCAN F . C : T h i s p r o g r a m u s e s s s c a n f to r e a d d a t a i t ems from


* a s t r i n g n a med t o k e n s t r i n g , t h e n d i s p l a y s t h em .
*I

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

v o i d ma i n ( )
(
cha r tokenst r i ng [ ] = " 15 12 14 . . . " ;
cha r s [81] ;
cha r c ;
i nt i:
fl o a t fp ;
721 sscanf

/* I n put v a r i o u s d a t a f rom t o k en s t r i n g : * /
s s c a n f C t o k e n s t r i ng , " % s " , s >:
s s c a n f C t o ken s t r i ng , " %c " , &c > :
s s c a n f C t o k en s t r i ng , " %d " , &i ) :
s s c a n f C t o k e n s t r i ng , " % f " , &fp > :

I * O u t p u t t h e d a ta read * /
p r i n t f C " St r i n g = %s \ n " , s >:
p r i n t f ( " C h a ra ct e r = %c\n " , c >:
p r i n t f C " I n t e ge r : = %d \ n " , i );
p r i n t f ( " Rea l : = %f\ n " , fp > :

Output

St r i n g 15
-

Cha racter 1-

I ntege r : = 1 5
Rea l : 1 5 . 000000
-
stackavail 122

Description Gets the size of the stack available.

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

size_t stackavail( void );

Remades The stackavail function returns the approximate size (in bytes) of the stack space available
for dynamic memory allocation with alloca.

Return Value The stackavail function returns the size in bytes as an unsigned integer value.

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

Exampm ��
����-

1 * ALLOC A� C : T h i s p ro 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
* a n d after u s i n g the a l l oc a f u n c 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 C " By t e s a v a i l a b l e on s t a c k : % u \ n " , s t a c ka v a i l ( ) ) ;

I * Al l o c a t e memo ry for s t r i n g . * /
b u f f e r = a l l oc a < 1 20 * s i z e o f ( c h a r ) ) ;
p r i n t f C " En t e r a s t r i n g : • > :
get s ( b u f f e r ) ;
p r i n t f C " Y o u e n t e red : % s \ n " , buffer ) ;

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

Output

Bytes a v a i l a b l e on s t a c k : 2028
Enter a s t r i n g : How muc h s t a c k s p a c e w i l l t h i s s t r i n g t a ke?
Y o u ente red : How m u c h s t a c k space wi l l t h i s s t r i n g t a k e ?
Byt e s a v a i l a b l e o n s t a c k : 1 902
723 stat

DBScrlpl/on Gets status infonnation on a file.

#include <Sys\stat.h>
#include <Sys\types.h>

int stat( char *pathname, struct stat *buffer );

pathname Path name of existing file


buffer Pointer to structure that receives results

Remarks The stat function obtains infonnation about the file or directory specified by pathname
and stores it in the structure pointed to by buffer. The stat structure, defined in the file
SYS\STAT.ff, includes 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 Drive number of the disk containing the file (same as
st_rdev). Real mode only.
st mode Bit mask for file-mode infonnation. The S IFDIR bit is set if
pathname specifies a directory; the S_IFREG bit is set if
pathname specifies an ordinary file. User read/write bits are
set according to the file's pennission mode; user execute bits
are set according to the file-name extension.

st mtime Time of last modification of file (same as st_atime and


st_ctime).
st nlink Always 1.
st rdev Drive number of the disk containing the file (same as st_dev) .
Real mode only.

st size Size of the file in bytes.

Note that ifpathname refers to a device, the size and time fields in the stat structure are
not meaningful.
stat 724

Return Value The stat function returns the value 0 if the file-status information is obtained. A return
value of -1 indicates an error, also, errno is set to ENOENT, indicating that the file name
or path name could not be found.

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

See Also access, fstat

/ * STAT . C : T h i s p r o g r a m u s e s t h e s t a t f u n c t i on t o r epo r t i n f o rma t i on


* a bo u t the f i l e n a med STAT . C .
*I

#i n c l u d e < t i me . h>
#i n c l u d e < sy s \ typ e s . h >
#i n c l u d e < sy s \ s ta t . h >
#i n c l u d e <stdi o . h>

v o i d ma i n ( )
{
s t r u c t s t a t buf ;
i nt fh , resul t ;
c h a r b u f fe r [ ] = " A l i n e t o o u t p u t " ;

/ * Get d a t a a s s o c i a t ed wi t h " s t a t . c " : * /


resul t = s t a t ( " s ta t . c " , &buf l ;

I * Check i f sta t i s t i c s a re v a l i d : */
i f ( res ul t != 0 l
p e r r o r ( " P r o b l em g e t t i ng i n f o rma t i on " ) ;
el se
{
I * O u tp u t s ome o f t h e s t a t i s t i c s : * /
p r i n t f ( " Fi l e s i z e % l d \ n " , b u f . s t_s i z e ) ;
pri ntf( " Dri ve %c : \ n " , b u f . s t_d ev + ' A ' ) ;
p r i n t f ( " T i me mod i f i ed : % s " , c t i me ( & b u f . st_a t i me l l ;

Output

F i l e s i ze 761
Dri ve C:
T i me mod i f i ed Wed J u n 1 4 1 2 : 2 0 : 08 1 9 89
725 _status87

Description Gets the floating-point status word.

#include <float.h>

unsigned int _status87( void );

Remarks The _status87 function gets the floating-point status word. The status word is a com­
bination of the 8087 /80287/80387 status word and other conditions detected by the
8087/80287/80387 exception handler, such as floating-point stack overflow and underflow.

Return Value The bits in the value returned indicate the floating-point status. See the FLOAT.ff include
file for a cmnplete definition of the bits returned by _status87.
Note that many of the math library functions modify the 8087 /80287 status word, with un­
predictable results. Return values from _clear87 and _status87 become more reliable as
fewer floating-point operations are performed between known states of the floating-point
status word.

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

See Also _clear87, _control87

Exampm _________________________________________________________________

I * STATUS87 . C : T h i s p r o g r a m c re a t e s va r i o u s f l o a t i n g - po i nt e r r o r s a nd
* t h e n u s e s _s t a t u s 8 7 t o d i s p l a y mes s a ges i n d i c a t i ng t h e s e p r o b l ems .
*I

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

v o i d ma i n ( )
(
d o u b l e a = l e -40 , b ;
fl oat x , y ;

p r i n t f ( " St a t u s - % . 4x - c l ea r \ n " , _s t a t us87 ( ) ) ;

I * As s i gnment i n t o y i s i n exa c t & u n d e r f l ows : * /


Y = a;
p r i n t f ( " St a t u s = % . 4x - i n exa c t , u n d e r f l ow\ n " , _s t a t us87 ( ) >:

I * y i s d e n o rma l : * /
b = y;
p r i n t f ( " S t a t u s - % . 4x - i n exa ct u n d e rf l ow , d e n o rma l \ n " , _s ta t u s 8 7 ( ) >:
_status87 726

I * C l ea r u s e r 8087 : * /
_c l e a r87 ( ) ;

Output

S t a t u s = 0000 - c l e a r
S t a t u s = 0030 - i n exa c t , u n d e r f l ow
Sta t u s = 0032 - i n exa ct u n d e r f l ow , d e n o rma l
727 strcat, _fstrcat

Description Append a string.

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

char *strcat( char *string], const char *string2 );


char _far * _far _fstrcat( char _far *string], const char _far *string2 );

string] Destination string

string2 Source string

Rematits The strcat and _fstrcat functions append string2 to string], terminate the resulting string
with a null character, and return a pointer to the concatenated string (stringl).

to these functions are expected to contain a null character ( '\0 ' ) marking the end of the
The strcat and _fstrcat functions operate on null-terminated strings. The string arguments

string. No overflow checking is performed when strings are copied or appended.

The _fstrcat function is a model-independent (large-model) form of the strcat function.


The behavior and return value of _fstrcat are identical to those of the model-dependent
function strcat, with the exception that the arguments and return values are far pointers.

Return Value The return values for these functions are described above.

Compatibility strcat

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

_fstrcat

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

See Also strncat, strncmp, strncpy, strnicmp, strrchr, strspn

I * STRCPY . C : T h i s p r o g r a m u s e s s t r c py a n d s t r c a t to b u i l d a p h ra s e . * /

#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strcat, _fstrcat 728

v o i d ma i n { )
(
c h a r s t r i n g [ 80 ] ;

s t r c py { s t r i ng , " He l l o worl d f rom • ) ;


strcat < s t r i ng , " s t rc py • ) ;
strcat ( s t r i ng , " a nd " ) ;
strcat { s t r i ng , " s t rc a t ! " ) ;
pri ntf( " St r i n g = %s\n " , stri ng ) ;

Output

St r i ng = H e l l o worl d from s t rcpy a n d s t rc a t !


729 strchr, _fstrchr

Description Find a character in a string.

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

char *strchr( const char *string, int c );


char _far * _far _fstrchr( const char _far *string, int c );

string Source string


c Character to be located

Remarks The strchr and _fstrchr functions return a pointer to the first occurrence of c in string.
The character c may be the null character ('\0'); the terminating null character of string is
included in the search. The function returns NULL if the character is not found.

The strchr and _fstrchr functions operate on null-terminated strings. The string argu­
ments to these functions are expected to contain a null character ('\0') marking the end of
the string.

The _fstrchr function is a model-independent (large-model) form of the strchr function.

function strchr, with the exception that the arguments and return values are far.
The behavior and return value of fstrchr are identical to those of the model-dependent

Return Value The return values for these functions are described above.

Compatibility strchr

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

_fstrchr

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

See Also strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strrchr, strspn, strstr

I * STRCHR . C : T h i s p r o g r a m i l l u s t ra t e s s ea r c h i ng f o r a c h a ra c t e r wi t h
* s t r c h r ( s e a r c h fo rwa rd ) o r s t r r c h r ( s e a r c h ba c kwa rd ) .
*I
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h >
strchr, _fstrchr 730

i nt ch = ' r ' :
char s t r i n g [ ] = " T h e q u i c k brown dog j umps o v e r t h e l a zy fox • :
char fmt l [ J = • 1 2 3 4 5" ;
c ha r fmt2 [ ] = " 1 234567890 1 2 34567890 1 2 3 4 5 6 7 89 0 1 2345678901 234 5 6 7 89 0 " ;

v o i d ma i n ( )
{
c h a r *pdes t :
i nt r e s u l t ;

p r i n t f C " St r i ng t o be s ea r c h ed : \ n \ t \ t % s \ n " , s t r i n g > :


p r i n t f C " \ t \ t%s \ n \ t \ t% s \ n \ n " , fmt l , fmt 2 > :
p r i n t f C • se a rc h c ha r : \ t % c \ n " , c h > :

I * Sea r c h f o rwa rd . * /
p d e s t = s t rc h r C s t r i ng , c h ) ;
resul t = pdest - stri ng + l ;
i f ( pdest ! = NULL )
p r i n t f C " Re s u l t : \ t f i r s t %c found a t p os i t i on %d \ n \ n • , c h , r e s u l t > :
el se
p r i n t f C " Re s u l t : \ t % c n o t found \ n " > :

I * Sea r c h b a c kwa rd . * /
pdes t = s t r rc h r C s t r i n g , c h > :
resul t - pdest - s t r i ng + 1 ;
i f ( pdest ! = NULL )
p r i n t f C " Re s u l t : \ t l a s t %c found a t pos i t i on % d \ n \ n " , c h , r e s u l t > :
el se
p r i n t f ( " Re s u l t : \ t % c not found \ n " > :

Output

St r i n g t o be s e a rched :
T h e q u i c k b rown dog j umps o v • r t h e l a zy fox
1 2 3 4 5
1 23456789012345678901 234567890 1 2345678901 2 34 5 67890

Sea r c h c h a r : r
Re s u l t : f i r s t r found a t po s i t i on 1 2

Res u l t : l a s t r found a t pos i t i on 30


731 strcmp, _fstrcmp

Description Compare strings.

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

int strcmp( const char *string] , const char *string2 );


int _far _fstrcmp( const char _far *string], const char _far *string2 );

stringl String to compare


string2 String to compare

Remarks The strcmp and _fstrcmp functions compare string] and string2 lexicographically and re­
turn a value indicating their relationship, as follows:

Value Meaning
<0 string] less than string2
=0 string] identical to string2
>0 string] greater than string2

The strcmp and _fstrcmp functions operate on null-terminated strings. The string argu­
ments to these functions are expected to contain a null character ( '\0 ' ) marking the end of
the string.

The _fstrcmp function is a model-independent (large-model) form of the strcmp function.


The behavior and return value of _fstrcmp are identical to those of the model-dependent
function strcmp, with the exception that the arguments are far pointers.
The strcmpi and stricmp functions are case-insensitive versions of strcmp.

Return Value The return values for these functions are described above.

Compatibility strcmp

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

_fstrcmp

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


strcmp, _lstrcmp 732

See Also memcmp, memicmp, strncat, strncmp, strncpy, strnicmp, strrchr, strspn

Exampre ��
��

I * STRCM P . C * /
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s t d i o . h >

c h a r s t r i n g l [ J = " T h e q u i c k b r own dog j umps o v e r t h e l a zy fox " ;


c h a r stri ng2 [ ] " T h e QU I C K b r own dog j umps o v e r t h e l a zy fox " ;

v o i d ma i n ( )
I
c h a r t mp [ 20 J ;
i n t res u l t ;

I * Case sensi ti ve */
p r i n t f ( " C ompa re s t r i n g s : \ n \ t % s \ n \ t % s \ n \ n " , s t r i n g l , s t r i ng2 ) ;
r e s u l t = s t rcmp ( s t r i n g l , s t r i n g 2 ) ;
i f ( resul t > 0 )
s t rcpy ( tmp , " g re a t e r t h a n " ) ;
el s e i f ( resul t < 0 )
s t r c py ( tmp , " l e s s t h a n " l ;
el se
s t rc py ( tmp , " eq u a l t o " l ;
p r i n t f ( " \ t s t rcmp : S t r i n g 1 i s %s s t r i n g 2 \ n " , tmp ) ;

/ * C a s e i n s en s i t i v e ( c o u l d u s e e q u i v a l e n t s t r i cmp l * /
r e s u l t = s t rcmp i ( s t r i n g l , s t r i n g 2 l ;
i f ( resul t > 0 l
s t r c py ( tmp , " g re a t e r t h a n " ) ;
el s e i f ( resul t < 0 l
s t r c py ( tmp , " l e s s t h a n " l ;
el s e
s t rc py ( tmp , " eq u a l t o " l ;
p r i n t f ( " \ t s t r cmp i : St r i n g 1 i s % s s t r i ng 2 \ n " , tmp l ;

Output

Compa re s t r i n g s :
T h e q u i c k b rown dog j umps o v e r t h e 1 a zy fox
The QU I C K b rown dog j umps o v e r t h e l a zy fox

s t rcmp : Stri ng 1 i s greater than stri ng 2


s t rcmp i : St r i ng 1 i s eq u a l t o s t r i n g 2
733 strcoll

Description Compares strings using locale-specific information.

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

int strcoll( const char *stringl, const char *string2 );

string] String to compare


string2 String to compare

Remarks The strcoll function compares string} and string2 lexicographically and returns a value in­
dicating their relationship, as follows:

Value Meaning

<0 string} less than string2


=O string] identical to string2
>0 string} greater than string2

The strcoll function operates on null-terminated strings. The string arguments to these
functions are expected to contain a null character ('\0') marking the end of the string.

The strcoll function differs from strcmp in that it uses locale-specific information to pro­
vide locale-specific collating sequences.

Return Value The return value for this function is described above.

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

See Also localeconv, setlocale, strcmp, strncmp, strxfrm


strcpy, _fstrcpy 734

Oest:rlpllan Copy a string.

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

char *strcpy( char *stringI , const char *string2 );


char _far * _far _fstrcpy( char _far *string] , const char _far *string2 );

string] Destination string

string2 Source string

Remarks The strcpy function copies string2, including the tenninating null character, to the loca­
tion specified by string], and returns string] .
The strcpy and _fstrcpy functions operate on null-tenninated strings. The string argu­
ments to these functions are expected to contain a null character ('\0 ' ) marking the end of
the string. No overflow checking is perfonned when strings are copied or appended.

The _fstrcpy function is a model-independent (large-model) fonn of the strcpy function.


The behavior and return value of _fstrcpy are identical to those of the model-dependent
function strcpy, with the exception that the arguments and return values are far pointers.

Return Value The return values for these functions are described above.

Campallblllty strcpy

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

_fstrcpy

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

See Also strcat, strcmp, strncat. strncmp, strncpy, strnicmp, strrchr, strspn

/ * STRC PY . C : T h i s p r o g r a m u s e s s t rcpy a n d s t r c a t to b u i l d a p h ra s e . * /

#i n c l u d e < s t r i ng . h >
#i n c l u d e < s t d i o . h >
735 strcpy, _fstrcpy

v o i d ma i n ( )
(
c h a r s t r i n g [ 80 ] ;

s t rc py ( stri ng , " He l l o w o r l d from • l;


s t rc a t ( stri ng , • s t r c py • l :
s t rc a t ( stri ng , • a nd • l :
s t rc a t ( stri ng , • strcat ! " l ;
pri ntf( " St r i n g • % s \ n " , stri ng l :

Output

St r i n g a H e l l o w o r l d f rom s t rcpy a n d S t rea t !


strcspn, _fstrcspn 736

Description Find a substring in a string.

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

size_t strcspn( const char *stringl, const char *string2 );


size_t _far _fstrcspn( const char _far *stringl, const char _far *string2 );

string] Source string

string2 Character set

Remarks The strcspn functions return the index of the first character in string 1 belonging to the set
of characters specified by string2. This value is equivalent to the length of the initial sub­
string of string] consisting entirely of characters not in string2. Tenninating null charac­
ters are not considered in the search. If stringl begins with a character from string2,
strcspn returns 0.
The strcspn and _fstrcspn functions operate on null-tenninated strings. The string argu­
ments to these functions are expected to contain a null character ( '\0 ' ) marking the end of
the string.
The _fstrcspn function is a model-independent (large-model) fonn of the strcspn func­
tion. The behavior and return value of_fstrcspn are identical to those of the model­
dependent function strcspn, with the exception that the arguments and return values
are far.

Return Value The return values for these functions are described above.

Compatibility strcspn

• ANSI • DOS • OSl2 • U NIX • XEN IX

_fstrcspn

D ANSI • DOS • OSl2 D UNIX D XENIX

See Also strncat, strncmp, strncpy, strnicmp, strrchr, strspn

Exampm ������
I * STRC S P N . C * /
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h >
737 strcspn, _fstrcspn

v o i d ma i n ( )
(
c h a r s t r i n g [ ] = � xy z a bc " ;
i n t pos ;

pos = strcspn C stri ng , " a b c " > :


p r i n t f ( " F i r s t a , b o r c i n %s i s a t c h a r a c t e r %d\n " , s t r i n g , p o s > :

Output

Fi r s t a , b o r c i n xyz a bc i s a t c h a r a c t e r 3
_strdate 138

DBBt:rlpllan Copies a date to a buffer.

#include <time.b>

char *_strdate( char *datestr );

datestr Current date

Remades The _strdate function copies the date to the buffer pointed to by datestr, fonnatted

mm/ d d / yy

where mm is two digits representing the month, dd is two digits representing the day of
the month, and y y is the last two digits of the year. For example, the string

1 2 / 0 5 / 88

represents December 5, 1 988.

The buffer must be at least nine bytes long.

Relum Value The _strdate function returns a pointer to the resulting text string datestr.

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

See A/BO asctime, ctime, gmtime, localtime, mktime, time, t7.set

Exampm �����--

1 * STRT I M E . C * /
#i n c l ude < t i me . 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 dbuffer [ 9 ] ;
cha r tbuffer [ 9 ] ;

_s t rd a t e C d b u f f e r > :
p r i n t f ( " T h e c u r rent d a te i s % s \ n " , d b u f f e r > :
_s t rt i me ( t b u f f e r ) ;
p r i n t f ( " T h e c u r rent t i me i s % s \ n " , t b u f f e r l :
739 _strdate

Output

T h e c u r rent d a t e i s 0 6 / 2 0 / 8 9
T h e c u r rent t i me i s 0 9 : 33 : 1 3
strdup Functions 740

Description Duplicate strings.

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

char *strdup( const char *string );


char _far * _far _fstrdup( const char _far *string );
char _near * _far _nstrdup( const char _far *string );

string Source string

Remarks The strdup function allocates storage space (with a call to malloc) for a copy of string and
returns a pointer to the storage space containing the copied string. The function returns
NULL if storage cannot be allocated.
The _fstrdup and _nstrdup functions provide complete control over the heap used for
string duplication. The strdup function returns a pointer to a copy of the string argument.
The space for the string is allocated from the heap specified by the memory model in use.
In large-data models (that is, compact-, large-, and huge-model programs), strdup allo­
cates space from the far heap. In small-data models (tiny-, small-, and medium-model pro­
grams), strdup allocates space from the near heap.
The strdup, _fstrdup, and _nstrdup functions operate on null-terminated strings. The
string arguments to these functions are expected to contain a null character (' \0 ' ) marking
the end of the string.
The _fstrdup function returns a far pointer to a copy of the string allocated in far memory
(the far heap). As with the other model-independent functions, the syntax and semantics of
these functions correspond to those of strdup except for the sizes of the arguments and re­
turn values. The _nstrdup function returns a near pointer to a copy of the string allocated
in the near heap (in the default data segment).

Return Value The return values for these functions are described above.

Compatlblllty strdup, _fstrdup, _nstrdup

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


741 strdup Functions

See Also strcat, strcmp, strncat, strncmp, strncpy, strnicmp, strrchr, strspn

Exampm ������-

1 * STRDU P . C * /
#i n c l u d e < s t r i n g . h>
#i n c l u d e < s t d i o . h >
#i n c l u d e < c on i o . h >
Ii i n c l u d e < d o s . h >

v o i d ma i n ( )
(
c h a r b u f f e r [ ] = " T h i s i s t h e b u f f e r text " ;
c h a r * n ews t r i n g ;

p r i n t f { " O r i g i n a l : % s \ n " , buffer ) ;


n ews t r i ng = s t rd u p < b u f f e r ) ;
p r i n t f ( " Copy : % s \ n " , news t r i ng ) ;

Output

O r i g i n a l : T h i s i s t h e buffer text
C o py : T h i s i s the buffer text
strerror, _strerror 742

D11t:1/pllon Gets a system error message (strerror) or prints a user-supplied error message Lstrerror).

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

char *strerror( int errnum );


char *_strerror( char *string );

errnum Error number

string User-supplied message

Remarks The strerror function maps errnum to an error-message string, returning a pointer to the
string. The function itself does not actually print the message; for that, you need to call an
output function such as printf.

If string is passed as NULL, _strerror returns a pointer to a string containing the system

terminated by the newline character ('\n ' ) .


error message for the last library call that produced an error. The error-message string is

If string is not equal to NULL, then _strerror returns a pointer to a string containing (in
order) your string message, a colon, a space, the system error message for the last library
call producing an error, and a newline character. Your string message can be a maximum
of 94 bytes long.

Unlike perror, _strerror alone does not print any messages. To print the message re­
turned by _strerror to stderr, your program will need an fprintf statement, as shown in
the following lines:

i f ( ( acces s ( " d a t a fi l e " , 2 ) ) == -1)


f p r i n t f ( _s t r e r r o r ( N U L L > > :

The actual error number for strerror is stored in the variable errno, which should be de­
clared at the external level. The system error messages are accessed through the variable
sys_errlist, which is an array of messages ordered by error number. The _strerror func­
tion accesses the appropriate error message by using the errno value as an index to the
variable sys_errlist. The value of the variable sys_nerr is defined as the maximum num­
ber of elements in the sys_errlist array.
To produce accurate results, _strerror should be called immediately after a library routine
returns with an error. Otherwise, the ermo value may be overwritten by subsequent calls.

Note that the strerror function under Microsoft C version 5.0 is identical to the version
4.0 strerror function. The name was altered to permit the inclusion in Microsoft C version
5.0 of the ANSI-conforming strerror function. The _strerror function is not part of the
ANSI definition but is instead a Microsoft extension to it; it should not be used where
portability is desired. For ANSI compatibility, use strerror instead.
743 strerror, _strerror

Rstum Value The strerror function returns a pointer to the error-message string. The string can be over­
written by subsequent calls to strerror.
The _strerror function returns the same value as strerror.

Campatlbll/ly strerror

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

_strerror

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

SBB Alra clearerr, ferror, perror

Example See the example for perror.


strftime 744 '

Dll8t:rlpBan Fonnats a time string.

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

size_t strftime( char *string, size_t maxsize, const char *format,


const struct tm *timeptr );

string Output string

maxsize Maximum length of string


format Fonnat control string
timeptr tm data structure

Remarks The strftime function fonnats the tm time value in timeptr according to the supplied
format argument and stores the result in the buffer string. At most, maxsize characters are
placed in the string.

Theformat argument consists of one or more codes; as in printf, the fonnatting codes are
preceded by a % sign. Characters that do not begin with a % sign are copied unchanged to
string. The LC_TIME category of the current locale affects the output fonnatting of
strftime.
The fonnatting codes for strftime are listed below:

Format Description

%a Abbreviated weekday name

%A Full weekday name

%b Abbreviated month name

%B Full month name

%c Date and time representation appropriate for the locale


%d Day of the month as a decimal number (0 1 - 3 1)
%H Hour in 24-hour fonnat (00 - 23)
%1 Hour in 12-hour format (01 - 12)
%j Day of the year as a decimal number (00 1 - 366)
%m Month as a decimal number (01 - 1 2)

%M Minute as a decimal number (00 - 59)


745 strftime

%p Current locale's AM/PM indicator for a 1 2-hour clock


%S Second as a decimal number (00 - 59)

%U Week of the year as a decimal number; Sunday is taken as the


first day of the week (00 - 53)

%w Weekday as a decimal number (0 - 6; Sunday is 0)


%W Week of the year as a decimal number; Monday is taken as
the first day of the week (00 53)
-

%x Date representation for current loc ale


%X Time representation for current locale
%y Year without the century as a decimal number (00 - 99)
%Y Year with the century as a decimal number

%z Time zone name or abbreviation; no characters if time zone is


unknown
%% Percent sign

Return Value The strftime function returns the number of characters placed in string if the total number
of resulting characters, including the terminating null, is not more than maxsi:e.

Otherwise, strftime returns 0, and the contents of the stririg are indeterminate.

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

See Also localeconv, setlocale, strxfrJD

Example See the example for perror.


stricmp, _lstricmp 746

D111t:tlpllan Compare strings without regard to case.

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

int stricmp( const char *string!, const char *string2 );


int _far _fstricmp( const char _far *string!, const char _far *string2 );

string! String to compare


string2 String to compare

Rema tics The stricmp and _fstricmp functions compare string! and string2 lexicographically and
return a value indicating their relationship, as follows:

Value Meaning

<0 string! less than string2


=0 string] identical to string2
>0 string] greater than string2

The stricmp and _fstricmp functions operate on null-terminated strings. The string argu­
ments to these functions are expected to contain a null character ('\0 ' ) marking the end of
the string.

The _fstricmp function is a model-independent (large-model) form of the stricmp func­


tion. The behavior and return value of_fstricmp are identical to those of the model­
dependent function stricmp, with the exception that the arguments are far pointers.

The strcmp function is a case-sensitive version of stricmp.

RBtum Value The return values for these functions are described above.

CampaUblllly stricmp

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

_fstricmp

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


747 stricmp, _fstricmp

See Also memcmp, memicmp, strcat, strcpy, stmcat, strncmp, strncpy, strnicmp, strrchr,
strset, strspn

Example See the example for strcmp.


strlen, _fstrlen 748

DescrlpUon Get the length of a string.

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

size_t strlen( const char *string );


size_t _fstrlen( const char _far *string );

string Null-tenninated string

Rsmadcs The strlen and _fstrlen functions return the length in bytes of string, not including the ter­
minating null character ('\0').
The _fstrlen function is a model-independent (large-model) fonn of the strlen function.
The behavior and return value of_fstrlen are identical to those of the model-dependent
function strlen, with the exception that the argument is a far pointer.

Return Va/us These functions return the string length. There is no error return.

Compatibility strlen

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

_fstrlen

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

Exampm ��������-
1 * ST R L E N . C * /
#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 c l ude < c on i o . h >
#i n c l ude < d o s . h >
749 strlen, _fstrlen

v o i d ma i n ( )
(
c h a r b u f fe r [ 6 1 ] = � H ow l on g a m I ? " ;
i n t l en ;

l en = s t r l e n ( b u f f e r ) ;
p r i n t f ( " ' % s ' i s %d c h a r a c t e r s l on g \ n • , buffe r , l e n ) ;

Output

' H ow l on g a m I ? ' i s 14 c h a r a c t e r s l on g
strlwr, _fstrlwr 750

Description Convert a string to lowercase.

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

char *strlwr( char *string );


char _far * _far _fstrlwr( char _far *string );

string String to be converted

Remarks The strlwr and _fstrlwr functions convert any uppercase letters in the given null­
tenninated string to lowercase. Other characters are not affected.
The _fstrlwr function is a model-independent (large-model) fonn of the strlwr function.
The behavior and return value of _fstrlwr are identical to those of the model-dependent
function strlwr, with the exception that the argument and return values are far pointers.

Return Value These functions return a pointer to the converted string. There is no error return.

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

See Also strupr

Exampm _________________________________________________________________

I * STRLW R . C : T h i s p ro g r a m u s e s s t r l w r a n d s t ru p r t o c r e a t e
* uppe r c a s e a n d l ow e rc a s e copi e s of a mi x ed - c a s e s t r i n g .
*I

#i n c l ude < s t r i n g . h >


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

v o i d ma i n ( )
{
c h a r s t r i n g [ 1 00 ] = " T h e S t r i n g t o End A l l St r i n g s ! " ;
c h a r * c o py l , *copy2 ;

copyl = strlwr( s t rd u p ( s t r i n g ) ) ;
c opy2 = strupr< s t rd u p ( s t r i n g > ) ;
pri ntf ( " M i xed : %s\ n " , stri ng ) ;
pri ntf( " Lowe r : % s \ n " , copy l > :
pri ntf ( " Upper : % s \ n " , copy2 > :
751 strlwr, _fstrlwr

Output

M i x e d : T h e S t r i n g t o E n d Al l S t r i n g s !
Lowe r : t h e s t r i n g to end a l l s t r i n g s !
U p pe r : THE ST R I N G TO E N D A L L STRI N G S !
strncat, _fstrncat 752

Description Appends characters of a string.

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

char *strncat( char *string] , const char *string2, size_t count );


char _far * _far _fstrncat( char _far *string] , const char _far *string2,
size_t count );

string] Destination string


string2 Source string
count Number of characters appended

Remarks The strncat and _fstrncat functions append, at most, the first count characters of string2
to string], terminate the resulting string with a null character ( '\0 ' ) , and return a pointer to
the concatenated string (string]). If count is greater than the length of string2, the length of
string2 is used in place of count.
The _fstrncat function is a model-independent (large-model) form of the strncat function.
The behavior and return value of _fstrncat are identical to those of the model-dependent
function strncat, with the exception that all the pointer arguments and return values are far
pointers.

Return Value The return values for these functions are described above.

Compatibility strncat

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

_fstrncat

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

See Also strcat, strcmp, strcpy, strncmp, strncpy, strnicmp, strrchr, strset, strspn

Example ������
I * ST RN CAT . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
753 strncat, _fstrncat

v o i d ma i n ( )
{
c h a r stri ng [80] = "Th i s i s the i n i t i a l stri ng ! " ;
c h a r s u f f i x [ ] = • e x t r a text t o a d d t o t h e s t r i n g . . . ;
"

/ * Comb i n e s t r i n g s w i t h no more t h a n 1 9 c h a r a c t e r s of s u f f i x : */
p r i n t f { " Be f o r e : % s \ n " , s t r i n g l ;
st rnca t C stri ng , suffi x , 1 9 l ;
p r i n t f ( " Aft e r : % s \ n " , s t r i n g ) ;

Output

B e f o r e : Th i s i s t h e i n i t i a l s t r i n g !
Aft e r : Th i s i s t h e i n i t i a l s t r i n g ! e x t r a t e x t t o add
strncmp, _fstrncmp 754

Description Compare characters of two strings.

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

int strncmp( const char *string] , const char *string2, size_t count );
int _far _fstmcmp( const char _far *string] , const char _far *string2, size_t count );

string] String to compare

string2 String to compare

count Number of characters compared

RemarkB The stmcmp and _fstrncmp functions lexicographically compare, at most, the first count
characters of string] and string2 and return a value indicating the relationship between the
substrings, as listed below:

Value Meaning

<0 string] less than string2


=0 string] equivalent to string2
>0 string] greater than string2

The stmicmp function is a case-insensitive version of strncmp.

The _fstrncmp function is a model-independent (large-model) form of the strncmp func­


tion. The behavior and return v alue of _fstrncmp are identical to those of the model­
dependent function strncmp, with the exception that all the arguments and return values
are far.

Return Value The return values for these functions are described above.

Campatlblllly strncmp

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

_fstrncmp

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

SBB AllO strcat, strcmp, strcpy, strncat, strncpy, strrchr, strset, strspn
755 strncmp, _lstrncmp

Examp• �������-.-�

I * ST RNCM P . C * /
#i n c l ude < s t r i n g . h >
#i n c l u d e < s t d i o . h >

c h a r s t r i n g l [ ] = " T h e q u i c k b rown d o g j umps o v e r t h e l a zy f ox • ;


c h a r s t r i ng 2 [ ] = " T h e Q U I C K b r own fox j umps o v e r t h e l a zy d og " ;

v o i d ma i n ( )
(
c h a r tmp [ 20 ] ;
i nt resul t ;

p r i n t f ( " Compa re s t r i n g s : \ n \ t \ t%s \ n \ t \ t%s \ n \ n " , s t r i n g l , s t r i n g 2 ) ;

p r i n t f ( " Fu n c t i on : \ t s t rn cmp ( f i r s t 1 0 c h a r a c t e r s on l y ) \ n " ) ;


r e s u l t = s t rn cmp ( s t r i n g l , s t r i n g 2 , 1 0 ) ;
i f ( res u l t > 0 )
s t rc py ( tmp , • g re a t e r t h a n " ) ;
el s e i f ( resul t < 0 )
s t rcpy ( tmp , " l e s s t h a n • ) ;
el se
s t rcpy ( tmp , • eq u a l t o " ) ;
p r i n t f ( " Re s u l t : \ t \ t St r i n g 1 i s %s s t r i n g 2 \ n \ n " , tmp ) ;

p r i n t f ( " Fu n ct i on : \ t s t r n i cmp ( f i r s t 1 0 c h a r a c t e r s o n l y ) \ n " ) ;


r e s u l t = s t rn i cmp ( s t r i n g l , s t r i n g 2 , 1 0 ) ;
i f ( res u l t > 0 )
s t rc py ( tmp , • g re a t e r t h a n • ) ;
el s e i f ( resul t < 0 )
s t rc py ( tmp , " l e s s t h a n • ) ;
el s e
s t rc py ( tmp , " eq u a l t o • ) ;
p r i n t f ( " Re s u l t : \ t \ t St r i n g 1 i s %s s t r i n g 2 \ n \ n " , tmp ) ;

Output

Comp a re s t r i n g s :
T h e q u i c k b rown dog j umps o v e r t h e l a zy fox
The QU I C K b rown fox j umps over the l a zy dog

F u n c t i on : s t rncmp ( f i r s t 1 0 c h a r a c t e r s o n l y )
Res u l t : St r i n g 1 i s g rea t e r t h a n s t r i ng 2

Funct i on : s t r n i cmp ( f i r s t 1 0 c h a r a c t e rs o n l y )
Res u l t : S t r i n g 1 i s equa l t o s t r i ng 2
strncpy, _fstrncpy 756

Description Copy characters of one string to another.

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

char *strncpy( char *string] , const char *string2, size_t count );


char _far * _far _fstrncpy( char _far *stringl , const char _far *string2,
size_t count );

stringl Destination string


string2 Source string
count Number of characters copied

Remarks The strncpy and _fstrncpy functions copy count characters of string2 to string] and re­
turn string]. If count is less than the length of string2, a null character ( '\0 ') is not ap­
pended automatically to the copied string. If count is greater than the length of string2, the
string] result is padded with null characters ( '\0 ' ) up to length count.
Note that the behavior of strncpy and _fstrncpy is undefined if the address ranges of the
source and destination strings overlap.

The _fstrncpy function is a model-independent (large-model) fonn of the strncpy func­


tion. The behavior and return value of _fstrncpy are identical to those of the model­
dependent function strncpy, with the exception that all the arguments and return values
are far.

Return Value The return values for these functions are described above.

Compaliblllty strncpy

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

_fstrncpy

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

See Also strcat, strcmp, strcpy, strncat, strncmp, strnicmp, strrchr, strset, strspn
757 strncpy, _fstrncpy

Exampm ��������-

1 * STRNCPY . C * /
#i n c l u d e < s t r i n g . 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 s t r i n g [ 1 00 ] = " Ca t s a re n i ce usua l l y " ;

p r i n t f ( " Be fo r e : % s \ n " , s t r i ng > :


s t r n c py ( s t r i n g , " Do g s " , 4 > :
s t rn c py ( s t r i n g + 9 , " mea n " , 4 > :
p r i n t f ( " A ft e r : %s \ n " , s t r i ng > :

Output

B e fo r e : C a t s a re n i c e u s u a l l y
Afte r : Dogs a re mea n u s u a l l y
strnicmp, _fstrnicmp 758

011St:tlpllan Compare characters of two strings without regard to case.

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

int strnicmp( const char *string!, const char *string2, size_t count );
int _far _fstrnicmp( const char _far *string], const char _far *string2, .
· size_t count );

string] String to compare

string2 String to compare

count Number of characters compared

Remarks The strnicmp and _fstrnicmp functions lexicographically compare (without regard to
case), at most, the first count characters of string! and string2 and return a value indicating
the relationship between the substrings, as listed below:

Value Meaning

<0 string! less than string2


=O string! equivalent to string2
>0 string! greater than string2

The strncmp function is a case-sensitive version of strnicmp.

The _fstrnicmp function is a model-independent (large-model) fonn of the strnicmp func­


tion. The behavior and return value of _fstrnicmp are identical to those of the model­
dependent function strnicmp, with the exception that all the arguments and return values
are far.

Return Value The return values for these functions are described above.

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

See Also strcat, strcmp, strcpy, strncat, strncpy, strrchr, strset, strspn

Example See the example for strncmp.


169 strnset, _fstrnset

D•t:tlptlan Initialize characters of a' string to a given character.

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

char •strnset( char •string, int c, size_t count );


char _far • _far _fstmset( char _far •string, int c, sb:e_t count );

string String to be initialized

c Character setting

count Number of characters set

character c and return a pointer to the altered string. If count is greater than the length of
RematlcB The stmset and fstrnset functions set, at most, the first count characters of string to the

string, the length of string is used in place of count.


The _fstmset function is a model-independent (large-model) form of the strnset function.
The behavior and return value of _fstrnset are identical to those of the model-dependent
function stmset, with the exception that all the arguments and return values are far.

Retum Value The return values for these functions are described above.

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

See A/BO strcat, strcmp, strcpy, strset

Examp� --
---

1 * STRNSET . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >

v o i d ma i n ( )
{
cha r stri n g [ l 5 ] = " Th i s i s a test " ;

/ * Set not mo re t h a n 4 c h a r a c t e r s of s t r i n g t o be * ' s * I


p r i n t f C " Before : % s \ n • , s t r i n g > ;
s t rn s et C s t r i n g , ' * ' , 4 ) ;
p r i n t f ( " Aft e r : % s \ n " , s t r i ng ) ;
strnset, _fstrnset 760

Output

Before : Thi s i s a test


Afte r : * * * * i s a t e s t
761 strpbrk, _lstrpbrk

Description Scan strings for characters in specified character sets.

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

char *strpbrk( const char *string] , const char *string2 );


char _far * _far _fstrpbrk( const char _far *string], const char _far *string2 );

string] Source string

string2 Character set

Remarks The strpbrk function finds the first occurrence in string] of any character from string2.
The terminating null character ( '\0 ' ) is not included in the search.
The _fstrpbrk function is a model-independent (large-model) form of the strpbrk func­
tion. The behavior and return value of _fstrpbrk are identical to those of the model­
dependent function strpbrk, with the exception that all the arguments and return values
are far.

Return Value These functions return a pointer to the first occurrence of any character from string2 in
string]. A NULL return value indicates that the two string arguments have no characters in
common.

Compatibility strpbrk

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

_fstrpbrk

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

See Also strchr, strrchr

Exampre ��������-
1 * ST R P B R K . C * /
#i n c l ude < s t r i n g . 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 s t r i n g [ 1 0 0 J = " T h e 3 men a n d 2 boy s a t e 5 p i g s \ n " ;
cha r *resul t ;
strpbrk, _fstrpbrk 762

I * Ret u r n p o i n t e r to f i rst ' a ' o r ' b ' i n " s t r i n g " */


p r i n t f ( " 1 : %s \ n " , s t r i n g > :
res u l t = s t rpb r k ( s t r i ng , " 0 1 23456789 " ) ;
p r i n t f ( " 2 : % s \ n " , r e s u l t++ > :
r e s u l t = s t rpb r k ( r e s u l t , " 0 1 23456789 " ) ;
p r i n t f ( " 3 : % s \ n " , r e s u l t++ ) :
·

r e s u l t = s t rpb r k ( r e s u l t , " 0 1 23456789 " > :


pri ntf ( " 4 : %s\n " , resul t > :

Output

1 : T h e 3 men a n d 2 boys a t e 5 p i g s

2 : 3 m e n a n d 2 boys a te 5 p i g s

3 : 2 boy s a t e 5 p i g s

4: 5 pi gs
763 strrchr, _lstrrchr

Description Scan a string for the last occurrence of a character.

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

char *strrchr( const char *string, int c );


char _far * _far _fstrrchr( const char _far *string, int c );

string . Searched string


c Character to be located

minating null character ('\0 ' ) is included in the search. (Use strchr to find the first occur­
Remarks The strrchr function finds the last occurrence of the character c in string. The string's ter­

rence of c in string.)

The _fstrrchr function is a model-independent (large-model) form of the strrchr func­


tion. The behavior and return value of fstrrchr are identical to those of the model­
dependent function strrchr, with the exception that all the pointer arguments and return
values are far pointers.

Return Value These functions return a pointer to the last occurrence of the character in the string. A
NULL pointer is returned if the given character is not found.

Compatibility strrchr

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

_fstrrchr

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

See Also strchr, strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strspn

Example __ ���������������������������������

I * STRC H R . 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 a rc h i n g f o r a c h a r a c t e r w i t h
* s t r c h r < s ea r c h forwa rd ) o r s t r rc h r ( s ea r c h ba c kwa rd ) .
*/
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strrchr, _fstrrchr 764

i nt ch = ' r ' ;
char s t r i n g [ ] = " Th e q u i c k b rown dog j umps o v e r t h e l a zy fox " ;
cha r fmt l [ J = 1 2 3 4 5" ;
cha r fmt2 [ J = " 1 234567890 1 234567890123456789012345678901 234567890 " ;

v o i d ma i n ( )
{
c h a r *pdes t ;
i n t res u l t ;

p r i n t f { " St r i n g t o b e s e a r c h ed : \ n \ t \ t % s \ n " , s t r i n g ) ;
p r i n t f ( " \ t \ t % s \ n \ t \ t % s \ n \ n " , fmt l , fmt2 ) ;
p r i n t f ( " Se a r c h c h a r : \ t %c \ n " , c h l ;

I * Sea r c h forwa rd . * /
p d e s t = s t rc h r ( s t r i n g , c h l :
res u l t = pdest - s t r i n g + 1 ;
i f ( pdest ! = N U L L )
p r i n t f ( " Re s u l t : \ t f i r s t %c found a t p os i t i on %d \ n \ n " , c h , res u l t l ;
el se
p r i n t f ( " Re s u l t : \ t% c n o t found \ n " l ;

I * S e a r c h b a c kwa rd . * /
pd e s t = s t r rc h r ( s t r i n g , c h l ;
re s u l t = pdest - s t r i n g + 1 ;
i f ( pdest ! = NULL l
p r i n t f ( " Re s u l t : \ t l a s t %c found a t po s i t i o n %d \ n \ n " , c h , r e s u l t l ;
el se
p r i n t f ( " Re s u l t : \ t%c n o t found \ n " ) ;

Output

St r i n g t o b e s e a r c h ed :
T h e q u i c k brown dog j umps o v e r t h e l a zy fox
1 2 3 4 5
1 23 4 5 6 7 890 1 2 345678901 234567 890 1 2 345678901 234 5 6 7 890

Sea r c h c h a r : r
Re s u l t : f i r s t r found a t pos i t i on 1 2

Re s u l t : l a s t r found a t po s i t i on 30
765 strrev, _fstrrev

Daer/pt/on Reverses characters of a string.

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

char *strrev( char *string );


char _far * _far _fstrrev( char _far *string );

string String to be reversed

Remarks The strrev function reverses the order of the characters in string. The tenninating null
character ( '\0 ' ) remains in place.
The _fstrrev function is a model-independent (large-model) fonn of the strrev function.
The behavior and return value of fstrrev are identical to those of the model-dependent
function strrev, with the exception that the argument and return v alue are far pointers.

Return Value These functions return a pointer to the altered string. There is no error return.

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

SBB A/so strcpy, strset

I * ST R R E V . C : T h i s p r o g r a m c h e c ks a n i n put s t r i n g to s e e w h et h e r i t i s a
* pa l i nd rome : t h a t i-s , w h e t h e r i t r e a d s t h e s a me f o rwa rd a n d b a c kwa rd .
*/

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

v o i d ma i n ( )
(
c h a r stri n g [ 100J :
i nt resul t :

p r i n t f ( " I n put a s t r i n g a n d I w i l l t e l l you i f i t i s a pa l i nd rome : \ n " > :


g et s ( s t r i n g > :
strrev, _fstrrev 766

I * Re v e r s e s t r i n g a n d c omp a re ( i gnore c a s e ) : * /
res u l t = s t rcmpi ( s t r i ng , s t r rev ( s t rdup ( s t r i n g > > ) ;
i f ( res u l t == 0 >
p r i n t f ( " T h e s t r i n g \ " % s \ " i s a p a l i nd rome \ n \ n " , s t r i n g ) ;
el se
p r i n t f ( " T h e s t r i n g \ " % s \ " i s n o t a pa l i nd rome\ n \ n " , s t r i n g > ;

Output

I n put a s t r i n g a n d I wi l l tel l y o u i f i t i s a p a l i nd r ome :


Abl e wa s I e r e I s a w E l ba
T h e s t r i n g " Ab l e wa s I e r e I s a w E l b a " i s a p a l i n d rome
767 strset, _fstrset

Daer/pt/an Set characters of a string to a character.

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

char *strset( char *string, int c ) ;


char _far * _far _fstrset( char _far *string, int c );

string String to be set


c Character setting

R1matlt8 The strset function sets all of the characters of string to c, except the tenninating null
character ('\0').

The _fstrset function is a model-independent (large-model) fonn of the strset function.


The behavior and return value of _fstrset are identical to those of the model-dependent
function strset, with the exception that the pointer arguments and return value are far
pointers.

Retum Value These functions return a pointer to the altered string. There is no error return.

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

S11 Alsa memset, strcat, strcmp, strcpy, strnset

Exampm ______________________________________________________________

I * ST RS ET . C * I
#i n c l ude < s t r i n g . h >
#i n c l ude , < s t d i o . h >

v o i d ma i n ( )
(
c h a r s t r i n g [ ] - " Fi l l t h e s t r i n g w i t h s omet h i n g " :

p r i n t f ( " Before : % s \ n " , s t r i n g > :


s t r s et ( s t r i n g , ' * ' > :
p r i n t f ( " Aft e r : % s \ n " , s t r i ng > :
strset, _fstrset 768

Output

B e f o r e : F i l l t h e s t r i n g w i t h s omet h i n g
Aft e r : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
769 strspn, _fstrspn

Descr/pUon Find the first substring.

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

size_t strspn( const char *string] , const char *string2 );


size_t _far _fstrspn( const char _far *string] , const char _far *string2 );

string] Searched string


string2 Character set

Rsmalks The strspn function returns the index of the first character in string] that does not belong
to the set of characters specified by string2. This value is equivalent to the length of the ini­
tial substring of string] that consists entirely of characters from string2. The null character
( '\0 ' ) tenninating string2 is not considered in the matching process. If string] begins with
a character not in string2, strspn returns 0.

The _fstrspn function is a model-independent (large-model) fonn of the strspn function.


The behavior and return value of _fstrspn are identical to those of the model-dependent
function strspn, with the exception that the arguments are far pointers.

Rslurn Va/us These functions return an integer value specifying the length of the segment in string] con­
sisting entirely of characters in string2.

Compallblllly strspn

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

_fstrspn

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

BBB Also strcspn, stmcat, strncmp, stmcpy, strnicmp, strrchr

ExamplB __________________________________________________________________�

I * STRS P N . C : T h i s p r o g r a m u s e s s t r s p n t o d e t e rmi n e t h e l en g t h of
* the s egment i n the s t r i n g " c a bb a g e " con s i s t i ng of a ' s , b ' s , a nd e ' s .
* I n o t h e r w o rd s , i t f i n d s t h e f i r s t n on - a bc l et t e r .
*I

#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strspn, _fstrspn 770

v o i d ma i n ( )
{
cha r stri ng [ ] = " cabbage • ;
i nt resul t ;

r e s u l t = s t rspn C s t r i n g , " a b c " ) ;


p r i n t f ( " T h e p o rt i o n of ' % s ' c o n t a i n i n g o n l y a , b , o r c •
" i s %d byt e s l on g \ n " , s t r i ng , r e s u l t ) ;

Output

T h e p o rt i on o f ' c a bb a g e ' c o n t a i n i n g o n l y a , b , o r c i s 5 byt e s l on g


771 strstr, _fstrstr

Daer/pl/on Find a substring.

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

char •strstr( const char *string] , const char •string2 );


char _far • _far _fstrstr( const char _far •string], const char _far •string2 );

stringI Searched string

string2 String to search for

R1matks The strstr function returns a pointer to the first occurrence of string2 in string1.

The _fstrstr function is a model-independent (large-model) form of the strstr function.


The behavior and return value of _fstrstr are identical to those of the model-dependent
function strstr, with the exception that the arguments and return value are far pointers.

R1tum Value These functions return either a pointer to the first occurrence of string2 in string] , or
NULL if they do not find the string.

Compal/blllty strstr

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

_fstrstr

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

s.. AIBo strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strrchr, strspn

ExampM __�����������������������������---

1 * STRSTR . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >

char str[) = " l a zy " ;


char stri ng [ ] = " The q u i c k b rown d o g j umps o v e r t h e l a zy fox " ;
char fmt l [ ] = • 1 2 3 4 5" ;
char fmt 2 [ ] - " 1 234567 890 1 234567890 1 2345678901 234567890 1 2 34567890 " :
strstr, _fstrstr 772

v o i d ma i n ( )
(
c h a r *pdest ;
i nt resul t ;

p r i n t f ( " St r i ng t o be sea r c h ed : \ n \ t% s \ n " , s t r i n g ) ;


p r i n t f C " \ t% s \ n \ t %s \ n \ n " , fmt l , fmt2 > ;

pdest = strstr( stri ng , str ) ;


resul t = pdest � s t r i ng + l ;
i f ( pdest I = NULL )
p r i n t f ( " % s found a t p o s i t i on %d\ n \ n " , s t r , r e s u l t ) ;
el se
p r i n t f C " %s not found \ n " , s t r ) ;

Output

St r i n g t o be s e a rched :
T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox
1 2 3 4 5
1 2 34567890 1 2345678901 234567890 1 234567890123456 7890

l a zy found at p o s i t i o n 3 6
_strtime

Daer/pl/an Copies the time to a buffer.

#include <time.h>

char *_strtime( char *timestr );

timestr Time string

Remalk8 The _strtime function copies the current time into the buffer pointed to by timestr. The
time is formatted

h h : mm : s s

where h h is two digits representing the hour in 24-hour notation, mm is two digits repre­
senting the minutes past the hour, and s s is two digits representing seconds. For ex­
ample, the string

1 8 : 23 : 44

represents 23 minutes and 44 seconds past 6:00 PM.


The buffer must be at least nine bytes long.

Retum Value The _strtime function returns a pointer to the resulting text string timestr.

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

See Also asctime, ctime, gmtime, localtime, mktime, time, tDet

Exampm ��
����---

1 * ST RT I M E . C * /
#i n c l u d e < t i me . h >
#i n c l u d e < s t d i o . h >

v o i d ma i n ( )
(
cha r dbuffer [ 9 ] ;
cha r tbuffer [ 9 ] ;
_strtime 774

_s t rd a t e C d b u f f e r >:
p r i n t f C • T h e c u r rent d a t e i s S s \ n • , dbuffer >:
_s t r t i me C t b u f f e r > :
p r i n t f C • T h e c u r r e n t t i me i s S s . \ n • , t b u f f e r >:

Output

The current date i s 0 6 / 20/ 89


T h e c u r r e n t t i me 1 $ 09 : 33 : 1 3
775 strtod, stria/, _strtold, strtou/

Description Convert strings to a double-precision (strtod, _strtold), long-integer (strtol), or unsigned


long-integer (strtoul) value.

#include <Stdlib.h>

double strtod( const char *nptr, char **endptr );


long strtol( const char *nptr, char **endptr, int base );
long double _strtold( const char *nptr, char **endptr );
unsigned long strtoul( const char *nptr, char **endptr, int base );

nptr String to convert


endptr End of scan
base Number base to use

Rematits The strtod, _strtold, strtol, and strtoul functions convert 'a character string to a double­
precision value, a long-double value, a long-integer value, or an unsigned long-integer
value, respectively. The input string is a sequence of characters that can be interpreted as a
numerical value of the specified type. If the strtod or _strtold function appears in a
compact-, large-, or huge-model program, nptr can be a maximum of 100 characters.

of a number. This may be the null character ( '\0 ' ) at the end of the string. With strtol or
These functions stop reading the string at the first character they cannot recognize as part

strtoul, this terminating character can also be the first numeric character greater than or
equal to base. If endptr is not NULL, a pointer to the character that stopped the scan is
stored at the location pointed to by endptr. If no conversion could be performed (no valid
digits were found or an invalid base was specified), the value of nptr is stored at the loca­
tion pointed to by endptr.

The strtod and _strtold functions expect nptr to point to a string with the following form:
[whitespace]) [sign]) [digits]) [.digits]) [ {d I D I e I E ) [sign])digits]]
The first character that does not fit this form stops the scan.
The strtol function expects nptr to point to a string with the following form:
[whitespace]) [sign]) [O]) [{ x I X }]] [digits])
The strtoul function expects nptr to point to a string having this form:
[whitespace]) [{ + 1 - } ]] [O]) [{ x I X } ]] [digits])
strtad, stria/, _strtald, strtaul 776

If base is between 2 and 36, then it is used as the base of the number. If base is 0, the ini­
tial characters of the string pointed to by nptr are used to determine the base. If the first
character is 0 and the second character is not 'x' or 'X', then the string is interpreted as an
octal integer; otherwise, it is interpreted as a decimal number. If the first character is 'O'
and the second character is 'x' or 'X', then the string is interpreted as a hexadecimal in­
teger. If the first character is ' l ' through '9', then the string is interpreted as a decimal in­
teger. The letters 'a' through ' z ' (or ' A' through Z ) are assigned the values 10 through
' '

35; only letters whose assigned values are less than base are permitted.
The strtoul function allows a plus (+) or minus (-) sign prefix; a leading minus sign indi­
cates that the return v alue is negated.

Retum Value The strtod and _strtold functions return the value of the floating-point number, except
when the representation would cause an overflow, in which case it returns ±HUGE_VAL.
The functions return 0 if no conversion could be performed or an underflow occurred.
The strtol function returns the value represented in the string, except when the repre­
sentation would cause an overflow, in which case it returns LONG_MAX or LONG_MIN.
The function returns 0 if no conversion could be performed.
The strtoul function returns the converted value, if any. If no conversion can be per­
formed, the function returns 0. The function returns ULONG_MAX on overflow. In all four
functions, ermo is set to ERANGE if overflow or underflow occurs.

Compatibility strtod, strtol, _strtold

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

strtoul

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

See Also atof, atol

I * ST RTO D . C : T h i s p r o g r a m u s e s s t r t o d to c o n v e r t a s t r i n g t o a
* d o u b l e - p r ec i s i on v a l u e ; s t r t o l t o c o n v e r t a s t r i n g t o l o ng
* i nt e g e r v a l ues ; and s t r t o u l t o c o n v e r t a s t r i n g t o u n s i gned
* l on g - i n t e g e r v a l u e s .
*I

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


#i n � l u d e < s t d i o . h >
777 strtod, stria/, _strtold, strtoul

v o i d ma i n ( )
(
cha r *stri ng , *stopstri ng ;
doubl e x ;
1 ong 1 ;
i nt ba s e ;
u n s i g n ed l on g u l ;

s t r i n g = " 3 . 1 4 1 5926Th i s s t opped i t " ;


x = s t rtod ( s t r i ng , & s t ops t r i n g l ;
pri ntf( " stri ng = %s\ n " , stri ng ) ;
pri ntf( " s t rtod = % f \ n " , x ) ;
pri ntf( " Stopped s c a n a t : % s \ n \ n " , s t o p s t r i ng l ;

s t r i n g = " - 1 0 1 1 0 1 34932Th i s s t opped i t " ;


1 = s t rt o l ( s t r i n g , & s t o p s t r i n g , 10 ) ;
pri ntf( " stri ng = %s\n " , stri ng l ;
pri ntf( " st rtol = %1 d\ n " , 1 l ;
pri ntf( " Stopped s c a n a t : % s \ n \ n " , s t o ps t r i n g l ;

s t r i n g = " 1 0 1 1 0 1 34932 " ;


pri ntf( " stri ng = %s\ n " , stri ng l ;
I * C o n v e rt s t r i n g u s i n g b a s e 2 , 4 , a nd 8 : * /
fo r ( b a s e = 2 ; b a s e <= 8 ; b a s e * = 2 )
(
/ * Convert the s t r i ng : */
u l = s t rt o u l ( s t r i n g , & s t o p s t r i n g , ba s e > :
pri ntf( • s t r t o l = % 1 d ( ba s e %d l \ n " , u l , ba s e ) ;
pri ntf( • Stopped s c a n a t : % s \ n " , s t o ps t r i n g ) ;

Output

s t r i n g = 3 . 1 4 1 5 9 2 6Th i s s t opped i t
s t r t od = 3 . 1 4 1 5 9 3
Stopped s c a n a t : T h i s s t opped i t

s t r i ng = - 1 0 1 1 0 1 34932Th i s s t opped i t
s t rt o l = - 2 1 4 7483647
St opped s c a n a t : T h i s s t opped i t

s t r i n g = 1 0 1 1 0 1 34 9 3 2
s t rt o l = 4 5 ( ba s e 2 )
St opped s c a n a t : 34932
s t rt o l = 4423 ( ba s e 4 )
Stopped s c a n a t : 4 9 3 2
s t rt o l = 2 1 34 1 08 ( ba s e 8 )
Stopped s c a n a t : 9 3 2
strtok, _fstrtok 778

D•crlpl/on Find the next token in a string.

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

char *strtok( char *string], const char *string2 ); .

char _far * _far _fstrtok( char _far *string], const char _far *string2 );

string] String containing token(s)


string2 Set of delimiter characters

Remam The strtok function reads string] as a series of zero or more tokens and string2 as the set
of characters serving as delimiters of the tokens in string]. The tokens in string] may be
separated by one or more of the delimiters from string2.
The tokens can be broken out of string] by a series of calls to strtok. In the first call to
strtok for string], strtok searches for the first token in string], skipping leading
delimiters. A pointer to the first token is returned. To read the next token from string I, call
strtok with a NULL value for the string] argument. The NULL string] argument causes
strtok to search for the next token in the previous token string. The set of delimiters may
vary from call to call, so string2 can take any value.
The _fstrtok function is a model-independent (large-model) fonn of the strtok function.
The behavior and return value of _fstrtok are identical to those of the model-dependent
function strtok, with the exception that the arguments and return value are far pointers.

serts a null character ('\0 ' ) after the token in stringI .


Note that calls to these functions will modify string], since each time strtok is called it in­

Retum Va/ue The first time strtok i s called, i t returns a pointer to the first token i n string]. In later calls
with the same token string, strtok returns a pointer to the next token in the string. A
NULL pointer is returned when there are no more tokens. All tokens are null-tenninated.

Compatlblllty strtok

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

_fstrtok

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


779 strtok, _lstrtok

See Also strcspn, strspn

I * STRTOK . C : I n t h i s p r o g r a m , a l oop u s e s s t rt o k t o p r i n t a l l t h e t o ke n s
* ( s epa ra ted b y comma s o r bl a n k s ) i n t h e s t r i n g n amed " s t r i n g • .
*I

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

c h a r s t r i n g [ ] = " A s t r i n g \ t o f , , t o k en s \ n a n d s ome more t o k e n s " ;


c h a r seps [ J = • , \t\n " ;
c h a r *token ;

v o i d ma i n ( )
{

p r i n t f ( " % s \ n \ nT o k e n s : \ n " , s t r i n g ) ;

/ * E s t a b l i s h s t r i n g a n d get t h e f i r s t t o ken : * /
t o k e n = s t rt o k ( s t r i n g , s eps l ;
whi l e ( token ! = NULL )
{
I * W h i l e t h e r e a re t o ke n s i n " s t r i n g • * /
pri ntf( • %s\ n • , token l ;
I * Get next t o k e n : * /
t o k e n = s t rt o k C N U L L , s e p s l ;

Output

A s t r i ng of , , tokens
a n d s ome more t o k e n s

Tokens :
A
s t ri n g
of
tokens
a nd
s ome
more
tokens
strupr, _fstrupr 780

Description Convert a string to uppercase.

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

char *strupr( char *string );


char _far * _far _fstrupr( char _far *string );

string String to be capitalized

Remarks These functions convert any lowercase letters in the string to uppercase. Other characters
are not affected.
The _fstrupr function is a model-independent (large-model) form of the strupr function.
The behavior and return value of _fstrupr are identical to those of the model-dependent
function strupr, with the exception that the argument and return value are far pointers.

Return Value These functions return a pointer to the converted string. There is no error return.

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

See Also strlwr

/ * STRLWR . C : T h i s p ro g r a m u s e s s t r l w r a n d s t r u p r · t o c re a t e
* upper c a s e a n d l ow e rc a s e cop i e s of a m i x ed - c a s e s t r i n g . ·
*I

#i n c l ude < s t r i n g . h>


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

v o i d ma i n ( )
{
c h a r s t r i n g [ 1 00 ] = " T h e St r i ng t o End Al l S t r i n g s ! " ;
c h a r * c o py l , *copy2 ;

copyl = strl wr< s t rd u p { s t r i n g ) > :


c opy 2 = strupr( s t rd u p ( s t r i n g ) > :
pri ntf{ " M i xed : %s\ n " , stri ng > :
pri ntf{ " Lowe r : % s \ n " , copy l > :
pri ntf( " Up pe r : % s \ n " , copy2 ) ;
781 strupr, _lstrupr

Output

M i xed : The S t r i n g t o End Al l St r i n g s !


Lowe r : t h e s t r i n g to end a l l s t r i n g s !
U p pe r : T H E S T R I N G TO E N O A L L STR I NG S !
strxfrm 782

Description Transfonns a string based on locale-specific infonnation.

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

size_t strxfrm( char *stringl , const char *string2, size_t count );

stringl String to which transfonned version of string2 is returned

string2 String to transfonn

count Maximum number of characters to be placed in stringl

Remarks The strxfrm function transfonns the string pointed to by string2 into a new fonn that is
stored in stringl. No more than count characters (including the null character) are trans­
fonned and placed into the resulting string.

The transfonnation is made using the infonnation in the locale-specific LC_COLLATE


macro.
After the transfonnation, a call to strcmp with the two transfonned strings will yield iden­
tical results to a call to strcoll applied to the original two strings.

The value of the following expression is the size of the array needed to hold the transfor­
mation of the source string:
1 + s t rx f rM( N U L L , · s t r i n g , 0 >

Currently, the C libraries support the "C" locale only; thus strxfrm is equivalent to the
following:

st r n c py ( _s t r i n g l , _s t r i n g 2 , _c ount > :
ret u r n ( s t r l en ( _s t r i ng2 ) > :

Return Value The strxfrm function returns the length of the transfonned string, not counting the tenni­
nating null character. If the return value is greater than or equal to count, the contents of
stringl are unpredictable.

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

See Also localeconv, setlocale, strncmp


783 swab

Dsscrlptlon Swaps bytes.

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

void swab( char *src, char *dest, int n );

src Data to be copied and swapped

dest Storage location for swapped data

n Number of bytes to be copied and swapped

Remarks The swab function copies n bytes from src, swaps each pair of adjacent bytes, and stores
the result at dest. The integer n should be an even number to allow for swapping. The
swab function is typically used to prepare binary data for transfer to a machine that uses a
different byte order.

Return Va/us None.

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

I* SWAB . C * /
#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 >

c h a r f r om [ ] = " BADC FEHGJ I LKNM PO RQTSVU XWZY " ;


char to[ ] = ". . . . . . . . . . . . . . . . . . . . . . . . . .n ;

v o i d ma i n ( )
{
p r i n t f ( " Be f o r e : \ t%s \ n \ t % s \ n \ n " , f rom , t o ) ;
s wa b ( f rom , t o , s i z e o f ( f rom ) ) ;
p r i n t f ( " Aft e r : \ t % s \ n \ t% s \ n \ n " , f rom , t o ) ;

Output

B e f o r e : BADC FEHGJ I L K N M P O RQTSVUXWZY

Aft e r : BADC F E H GJ I L K N M P O RQTSV U XWZY


ABCDE FGH I J K LM N O P Q RSTU V W X Y Z
system 784

Description Executes a command.

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

#include <Stdlib.h> Use STDLIB.H for ANSI compatibility

int system( const char *command );

command Command to be executed

Remarks The system function passes command to the command interpreter, which executes the
string as an operating-system command. The system function refers to the COMSPEC and
PATH environment variables that locate the command-interpreter file (the file named
COMMAND.COM in DOS or CMD.EXE in OS/2). If command is a pointer to an empty
string, the function simply checks to see whether or not the command interpreter exists.

Return Value If command is NULL and the command interpreter is found, the function returns a nonzero
value. If the command interpreter is not found, it returns the value 0 and sets errno to
ENOENT. If command is not NULL, the system function returns the value 0 if the com­
mand interpreter is successfully started. Under OS/2, the system function returns the exit
status from the command interpreter.

A return value of -1 indicates an error, and errno is set to one of the following values:

Value Meaning

E2BIG In DOS, the argument list exceeds 128 bytes, or the space re­
quired for the environment information exceeds 32K. In OS/2,
the combined argument list and space required for environ­
ment information exceed 32K.
ENOENT The command interpreter cannot be found.
ENOEXEC The command-interpreter file has an invalid format and is not
executable.
ENOMEM Not enough memory is available to execute the command; or
the available memory has been corrupted; or an invalid block
exists, indicating that the process making the call was not allo­
cated properly.
785 system

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

See Also exec functions, exit, _exit, spawn functions

Exampm _________________________________________________________________

I * SYSTEM . C : T h i s p r o g r a m u s e s sy s t em t o TY P E i t s s o u r c e f i l e . * /

#i n c l ude < p roce s s . h >

v o i d ma i n ( )
{
s y s t e m < " type system . c " > ;

Output

I * SYSTEM . C : T h i s p rog r a m u s e s sy s t em t o TY P E i t s s o u r c e f i l e . * /

#i n c l u d e <p roces s . h >

v o i d ma i n ( )
{
s y s t e m ( " type system . c " ) ;
tan Functions 786

Description Calculate the tangent (tan and tanl) and hyperbolic tangent (tanh and tanhl).

#include <math.h>

double tan( double x );


double tanh( double x );
long double tanl( long double x );
long double tanhl( long double x );

x Angle in radians

Remades The tan functions return the tangent or hyperbolic tangent of their arguments. The list
below describes the differences between the various tangent functions:

Function Description

tan Calculates tangent of x

tanh Calculates hyperbolic tangent of x

tanI Calculates tangent of x (80-bit version)

tanhl Calculates hyperbolic tangent of x (80-bit version)

The tanl and tanhl functions are the 80-bit counterparts and use an 80-bit, 1 0-byte co­
processor 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 tan function returns the tangent of x. If x is large, a partial loss of significance in the
result may occur; in this case, tan sets errno to ERANGE and generates a PLOSS error. If
x is so large that significance is totally lost, tan prints a TLOSS error message to stderr,
sets ermo to ERANGE, and returns 0.
There is no error return for tanh.

Compatiblllty tan, tanh

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

tanl, tanhl

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


181 tan Functions

S11 A/BO acos functions, asin functions, atan functions, cos functions, sin functions

I * TAN . C : T h i s p r o g r a m d i s p l a y s t h e t a n gent of p i I 4 a n d t h e hyperbol i c


* t a ngent o f t h e r e s u l t .
*/

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

v o i d ma i n ( )
(
doubl e pi - 3 . 141 5926535 :
doubl e x , Y:

x = ta n ( p i I 4 > :
y - tanh C x > :
pri ntfC " ta n ( %f ) =%f\ n " , x , y ) ;
p r i n t f C " t a n h C %f ) = % f \ n " , y , x ) ;

Output

t a n ( 1 . 000000 > 0 . 7 6 1 594


=

t a n h C 0 . 7 6 1 594 ) = 1 . 000000
tell 788

Description Gets the position of the file pointer.

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

long tell( int handle ) ;

handle Handle referring to open file

Remarks The tell function gets the current position of the file pointer (if any) associated with the
handle argument. The position is expressed as the number of bytes from the beginning of
the file.

Return Value A return value of -lL indicates an error, and errno is set to EBADF to indicate an invalid
file-handle argument. On devices incapable of seeking, the return value is undefined.

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

See Also ftell, lseek

/ * T E L L . C : T h i s p r o g r a m u s e s t e l l t o t e l l t h e f i l e p o i n t e r po s i t i on
* a ft e r a f i l e r ea d .
*I

#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 u d e < f c n t l . h >

v o i d ma i n ( )
[
i nt f h ;
l on g p o s i t i on ;
c h a r buffe r [ 500 ] ;

i f ( ( f h = open ( " te l l . c " , O_RDO N LY ) ) ! = - 1 )


{
i f ( r ea d ( f h , buff e r , 500 ) > 0
p r i n t f ( " C u r rent f i l e po s i t i on i s : % d \ n " , t e l l ( f h ) ) ;
789 tell

c l os e ( f h ) ;

Output

C u r rent fi l e p o s i t i on i s : 4 2 5
tempnam, tmpnam 790

Description Create temporary file names.

#include <Stdio.h>

char *tempnam( char *dir, char *prefix );


char *tmpnam( char *string );

string Pointer to temporary name

dir Target directory to be used if TMP not defined

prefix File-name prefix

Remarks The tmpnam function generates a temporary file name that can be used to open a tem­
porary file without overwriting an existing file. This name is stored in string. If string is
NULL, then tmpnam leaves the result in an internal static buffer. Thus, any subsequent
calls destroy this value. If string is not NULL, it is assumed to point to an array of at least
L_tmpnam bytes (the value of L_tmpnam is defined in STDIO.H). The function will
generate unique file names for up to TMP_MAX calls.

The character string that tmpnam creates consists of the path prefix, defined by the entry
P_tmpdir in the file STDIO.H, followed by a sequence consisting of the digit characters
'O' through 9 ; the numerical value of this string can range from 1 to 65,535. Changing
' '

the definitions of L_tmpnam or P_tmpdir in STDIO.H does not change the operation of
tmpnam
The tempnam function allows the program to create a temporary file name for use in
another directory. This file name will be different from that of any existing file. The
prefix argument is the prefix to the file name. The tempnam function uses malloc to allo­
cate space for the file name; the program is responsible for freeing this space when it is no
longer needed. The tempnam function looks for the file with the given name in the follow­
ing directories, listed in order of precedence:

Directory Used Conditions

Directory specified by TMP TMP environment variable is set, and


directory specified by TMP exists.
dir argument to tempnam TMP environment variable is not set, or
directory specified by TMP does not exist
P_tmpdir in STDIO.H The dir argument is NULL, or dir is name
of nonexistent directory.
Current working directory P_tmpdir does not exist.
791 tempnam, tmpnam

If the search through the locations listed above fails, tempnam returns the value NULL.

R1turn Value The tmpnam and tempnam functions both return a pointer to the name generated, unless
it is impossible to create this name or the name is not unique. If the name cannot be
created or if a file with that name already exists, tmpnam and tempnam return the value
NULL.

Compatibility tmpnam

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

tempnam

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

811 A/so tmpfile

I* T E M P NAM . C : T h i s p r o g r a m u s e s tmp n a m t o c re a t e a un i q u e fi l e n a me i n
* t h e c u r r e n t wo r k i n g d i rectory , t h en u s e s temp n a m t o c re a t e a u n i q u e
* f i l e name w i t h a p r e f i x o f s t q .
*I

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

v o i d ma i n ( )
{
c h a r * n a me l , * n a me 2 ;

I * C re a t e a t empo r a ry f i l e n a me f o r t h e c u r rent wo r k i n g d i rectory : * /


i f ( C namel tmpn a m ( N U L L ) ) ! = N U L L )
p r i n t f ( " % s i s s a fe t o u s e a s a t empo r a r� f i l e . \ n " , n a m e l > :
=

el se
p r i n t f ( " C a nnot c re a t e a u n i q u e f i l e n a me \ n " ) ;

I * C re a t e a t empo ra ry f i l e n a me i n t empo ra ry d i rectory w i t h t h e


* p refi x • s tq " . T h e a c t u a l d e s t i n a t i on d i rect o ry m a y v a ry depend i n g
* on t h e s t a t e of t h e TMP e n v i ronment v a r i a b l e a n d t h e g l oba l v a r i a b l e
* P_tmpd i r .
*I
i f ( ( n a me 2 = temp n a m ( " c : \ \ tmp " , " s t q " ) ) ! = N U L L )
p r i n t f ( " % s i s s a fe to u s e a s a tempo ra ry f i l e . \ n " , n a me2 > :
el se
p r i n t f ( " Ca nnot c re a t e a u n i q u e f i l e n a me \ n " > :
tsmpnam, tmpnam 792

Output

\ 2 i s s a fe t o u s e a s a tempo ra ry f i l e .
C : \ TM P \ s t q 2 i s s a f e t o u s e a s a tempora ry f i l e .
793 time

Description Gets the system time.

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

time_t time( time_t *timer );

timer Storage location for time

Rematks The time function returns the number of seconds elapsed since 00:00:00 Greenwich mean
time (GMT), January 1 , 1 970, according to the system clock. The system time is adjusted
according to the timezone system variable, which is explained in the tzset reference
section.

The return value is stored in the location given by timer. This parameter may be NULL, in
which case the return value is not stored.

Retum Value The time function returns the time in elapsed seconds. There is no error return.

Campal/blllty • ANSI • DOS • OS/2 • U N IX • XENIX

See Also asctime, ftime, gmtime, localtime, tzset, utime

I * CT I M E . C : T h i s p r o g r a m g e t s t h e c u r r e n t t i me i n t i me_t form , t h e n u s e s
* c t i me t o d i s p l a y t h e t i me i n s t r i n g form .
*/

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

v o i d ma i n ( )
(
t i me_t l t i me ;

t i me C & 1 t i me ) ;
p r i n t f C " T h e t i me i s % s \ n " , c t i me ( & l t i me ) ) ;

Output

T h e t i me i s T h u J u n 1 5 1 6 : 08 : 18 1 989
tmpfile 794

Description Creates a temporary file.

#include <Stdio.h>

FILE *tmptile( void );

Remarks The tmptile function creates a temporary file and returns a pointer to that stream. If the
file cannot be opened, tmptile returns a NULL pointer.

This temporary file is automatically deleted when the file is closed, when the program ter­
minates normally, or when rmtmp is called, assuming that the current working directory
does not change. The temporary file is opened in w+b (binary read/write) mode.

Return Value If successful, the tmpfile function returns a stream pointer. Otherwise, it returns a NULL
pointer.

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

See Also rmtmp, tempnam, tmpnam

/ * TM P F I L E . C : T h i s p ro g r a m u s e s tmp f i l e to c re a t e a t empora ry f i l e ,
* t h en d e l e t e s t h i s f i l e w i t h rmtmp .
*I

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

v o i d ma i n ( )
(
F I LE *st ream ;
c h a r temp s t r i n g [ ] = " St r i n g t o be w r i t t en " ;
i nt i ;

/ * C r e a t e t empo r a ry f i l e s . * /
f o r C i = 1 ; i <= 1 0 ; i ++ >
(
i f ( ( s t r eam = tmp f i l e ( ) ) == N U L L )
p e r ro r ( " C o u l d n o t open n ew temp o r a ry f i l e \ n " > :
el se
p r i n t f ( " Temp o r a ry f i l e % d w a s c re a t ed \ n " , i > :

I * Remov e t empo ra ry f i l es . * /
795 tmpfile

p r i n t f ( " %d t empo ra ry f i l e s d e l eted \ n " , rmtmp ( ) ) ;

Output

Temp o r a ry f i l e 1 wa s c r e a t ed
Tempo ra ry f i l e 2 wa s c re a t ed
Temp o r a ry f i l e 3 wa s c re a t ed
Tempo ra ry f i l e 4 wa s c r ea ted
Tempo ra ry f i l e 5 wa s c re a t ed
Tempo ra ry f i l e 6 wa s c re a t ed
Temp o r a ry f i l e 7 w a s c re a t ed
Temp o r a ry f i l e 8 wa s c r ea t ed
Tempo ra ry f i l e 9 wa s c re a t ed
Tempo ra ry f i l e 10 wa s c re a ted
1 0 temp o r a ry f i l e s d e l eted
toascii, tolower, toupper Functions 796

Dest:rlpllan Convert characters.

#include <ctype.h>

int toascii( int c ) ;


int tolower( int c );
int _tolower( int c ) ;
int toupper( int c );
int _toupper( int c ) ;

c Character to be converted

Remarks The toascii, tolower, _tolower, toupper, and _toupper routines convert a single charac­
ter, as described below:

Function Description

toascii Converts c to ASCII character


tolower Converts c to lowercase if appropriate

_tolower Converts c to lowercase

toupper Converts c to uppercase if appropriate

_toupper Converts c to uppercase

The toascii routine sets all but the low-order 7 bits of c to 0, so that the converted value
represents a character in the ASCII character set. If c already represents an ASCII charac­
ter, c is unchanged.
The tolower and _tolower routines convert c to lowercase if c represents an uppercase let­
ter. Otherwise, c is unchanged. The _tolower routine is a version of tolower to be used
only when c is known to be uppercase. The result of _tolower is undefined if c is not an
uppercase letter.
The toupper and _toupper routines convert c to uppercase if c represents a lowercase let­
ter. Otherwise, c is unchanged. The _toupper routine is a version of toupper to be used
only when c is known to be lowercase. The result of _toupper is undefined if c is not a
lowercase letter.
797 toascii, tolower, toupper Functions

Note that these routines are implemented both as functions and as macros. To conform
with the ANSI specification, the tolower and toupper routines are also implemented as
functions. The function versions can be used by removing the macro definitions through
#undef directives or by not including CTYPE.H. Function declarations of tolower and
toupper are given in STDLIB.H.
If the -Za compile option is used, the macro form of toupper or tolower is not used be­
cause it evaluates its argument more than once. Since the arguments are evaluated more
than once, arguments with side effects would produce potentially bad results.

Return Value The toascii, tolower, _tolower, toupper, and _toupper routines return the converted char­
acter c. There is no error return.

Compatlblllty toascii, _tolower, _toupper

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

tolower, toupper

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

See Also is functions

Exampm _________________________________________________________________

I * TOU P P E R . C : T h i s p r o g r a m u s e s t o u p p e r a n d t o l owe r to a n a l y z e a l l
* c h a r a c t e r s between 0x0 a n d 0x7 F . I t a l s o a pp l i e s _t o u p p e r a n d _t o l owe r
* t o a ny c o d e i n t h i s r a n g e f o r w h i c h t h e s e f u n c t i on s ma ke s en s e .
*I

#i n c l u d e < c o n i o . h >
#i n c l u d e < c ty p e . h >
#i n c l u d e < s t r i n g . h >

c h a r ms g [ ) = • some of TH E S E l et t e r s a r e Ca p i t a l s \ r \ n " ;
c h a r *p ;

v o i d ma i n ( )
(
c p ut s C m s g ) ;
toascii, tolower, toupper Functions 798

I * Rev e r s e c a s e of mes s a g e . * /
f o r e p = m s g ; p < m s g + s t r l en C m s g > : p++ )
(
i f ( i s l owe r C *p ) >
p u t c h C _t ouppe r C *p >:
e l s e i f ( i s uppe r C *p >
putc h C _t o l owe r C *p >:
el s e
putc h C *p > :

Output

Some of T H E S E l et t e r s a r e C a p i t a l s
s O M E O F t h e s e L ETT E RS A R E CAP I TA L S
199 tzset

Duer/pt/an Sets time environment variables.

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

void tmet( void );


int daylight; Global variables set by function
long timezone;
char *tzname[2]

Rematks The tmet function uses the current setting of the environment variable TZ to assign values
to three global variables: daylight, timezone, and tzname. These variables are used by the
ftime and localtime functions to make corrections from Greenwich mean time (GMT) to
local time, and by time to compute GMT from system time.

The value of the environment variable TZ must be a three-letter time-zone name, such as
PST, followed by an optionally signed number giving the difference in hours between
GMT and local time. The number may be followed by a three-letter daylight-saving-time
(DST) zone, such as PDT. For example, "PST8PDT" represents a valid TZ value for the
Pacific time zone. If DST is never in effect, as is the case in certain states and localities,
TZ should be set without a DST zone.

If the TZ value is not currently set, the default is PST8PDT, which corresponds to the
Pacific time zone.

Based on the TZ environment variable value, the following values are assigned to the vari­
ables daylight, timezone, and tzname when tmet is called:

Variable Value

daylight Nonzero value if a daylight-saving-time zone is specified in


the TZ setting; otherwise, 0
·

timezone Difference in seconds between GMT and local time


tzname[O] String value of the three-letter time-zone name from the TZ
setting
tzname [ l ] String value of the daylight-saving-time zone, or an empty
string if the daylight-saving-time zone is omitted from the TZ
setting

The default for daylight is I ; for timezone, 28,800; for tzname[O], PST; and for
tzname[ l ] , PDT. This corresponds to "PST8PDT."
If the DST zone is omitted from the TZ settings, the daylight variable will be 0 and the
ftime, gmtime, and localtime functions will return 0 for their DST flags.
tzset 800.

Retum Va/us None.

Compallblllly D ANSI • DOS • OS/2 • U NIX • XENIX

SBB A/so asctime, ftime, gmtime, localtime, time

I * T Z S ET . C : T h i s p r o g r a m f i r s t s et s up t h e t i me zone by pl a c i ng t h e v a ri a b l e
* n a med TZ=EST5 i n t h e e n v i ronment t a b l e . I t t h en u s e s t z s et to s e t t h e
* g l oba l v a r i a b l e s n a med d a y l i g h t , t i me z o n e , a nd t z n a me .
*I

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


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

v o i d ma i n ( )
(

i f ( p u t en v ( " TZ=EST 5 E DT " ) -1 )


(
p r i n t f ( " U n a b l e to s et TZ \ n " > :
exi t ( 1 > :
I
el se
(
t z s et ( ) ;
pri ntf( " dayl i ght = %d\n " , dayl i ght > :
pri ntf ( " t i me z o n e = % l d \ n " , t i mezone > :
pri ntf( " t z n a me [ 0 ] = % s \ n " , t z n a me [ 0 ] > :

Output

d a y l i g ht = 1
t i mezone = 1 8000
t z n a me [ 0 ] = E ST
801 ultoa

Description Converts an unsigned long integer to a string.

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

char *ultoa( unsigned long value, char *string, int radix );

value Number to be converted


string String result
radix Base of value

Rematics The ultoa function converts value to a null-tenninated character string and stores the result
(up to 33 bytes) in string. No overflow checking is perfonned. The radix argument speci­
fies the base of value; it must be in the range 2-36.

Return Value The ultoa function returns a pointer to string. There is no error return.

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

See Also itoa, ltoa

I * I TOA . C : T h i s p r o g r a m c o n v e r t s i n t e g e r s of v a r i ous s i zes t o s t r i n g s


* i n v a r i o u s ra d i x e s .
*I

#i n c l u d e < 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 b u f fe r [ 20 ] ;
i nt 1 = 344 5 ;
l on g l = -344 1 1 5 L ;
u n s i gned l on g u l 1 2 34567 890U L ;
=

i t oa { i , b u f fe r , 1 0 ) ;
pri ntf{ " St r i ng of i n t e g e r %d { r a d i x 1 0 ) : % s \ n " , i , b u f f e r > :
i t oa { i , b u f fe r , 1 6 ) ;
p r i ntf { " St r i n g of i n t e g e r %d { ra d i x 1 6 ) : 0x%s \ n " , i , buffer > :
i t oa { i , b u f fe r , 2 ) ;
p r i ntf { " St r i n g of i n t e g e r %d { ra d i x 2 ) : % s \ n " , i , b u f f e r > :
ultoa 802

l t oa C l , buffe r , 1 6 ) ;
p r i n t f ( " St r i ng o f l on g i n t % l d ( ra d i x 1 6 ) : 0x%s \ n • , 1 , buffer ) ;

u l t o a ( u l , buffe r , 1 6 ) ;
p r i n t f ( • st r i ng o f u n s i gned l on g % l u < ra d i x 1 6 ) : 0x% s \ n • , u l , buffer > :

Output

Stri ng of i n t e g e r 3445 ( ra d i x 1 0 ) : 3445


Stri ng of i n t e g e r 3445 ( ra d i x 1 6 ) : 0xd 7 5
S t r i ng of i n t e g e r 3 4 4 5 ( ra d i x 2 ) : 1 1 0 10 1 1 1 0 1 0 1
Stri ng of l on g i nt - 344 1 1 5 < ra d i x 1 6 ) : 0xfffa bfcd
Stri ng of u n s i gned l on g 1 234 5 6 7890 ( ra d i x 1 6 ) : 0x499602d2
803 umask

D•crlptlon Sets the default file-pennission mask.

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

int umask( int pmode );

pmode Default pennission setting

Rsmatks The umask function sets the file-pennission mask of the current process to the mode
specified by pmode. The file-pennission mask is used to modify the permission setting of
new files created by creat, open, or sopen. If a bit in the mask is 1 , the corresponding bit
in 'the file's requested pennission value is set to 0 (disallowed). If a bit in the mask is 0, the
corresponding bit is left unchanged. The pennission setting for a new file is not set until
the file is closed for the first time.

The argument pmode is a constant expression containing one or both of the manifest con­

they are joined with the bitwise-OR operator ( I ). The meaning of the pmode argument is
stants S_IREAD and S_IWRITE, defined in SYS\STAT.H. When both constants are given,

as follows:

Value Meaning
S_IREAD Reading not allowed (file is write-only)
S_IWRITE Writing not allowed (file is read-only)

For example, if the write bit is set in the mask, any new files will be read-only.

Note that under DOS and OS/2, all files are readable-it is not possible to give write-only
pennission. Therefore, setting the read bit with umask has no effect on the file's modes.

Rltum Va/us The umask function returns the previous value ofpmode. There is no error return.

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


umask 804

See Also chmod, creat, mkdir, open

I * UMASK . C : T h i s p r o g r a m u s e s uma s k to set t h e f i l e - p e rmi s s i on ma s k s o


* t h a t a l l f u t u r e f i l e s w i l l be c re a t e d a s r ea d - on l y f i l e s . I t a l s o
* d i s p l a y s t h e o l d ma s k .
*I

# i n c l ude < s y s \ types . h >


#i n c l ude < sy s \ s ta t . h >
//i n c l u d e < i o . h>
#i n c l u d e <stdi o . h>

v o i d ma i n ( )
{
i n t o l dma s k :

I * C r e a t e rea d - on l y f i l e s : * /
o l dma s k = uma s k C S_I W R I T E > :
p r i n t f ( " Ol dma s k = 0x% . 4x \ n " , o l dma s k > :

Output

O l dma s k = 0x0000
805 ungetc

Description Pushes a character back onto the stream.

#include <Stdio.h>

int ungetc( int c, FILE *stream );

c Character to be pushed
stream Pointer to FILE structure

Remarks The ungetc function pushes the character c back onto stream and clears the end-of-file in­
dicator. The stream must be open for reading. A subsequent read operation on the stream
starts with c. An attempt to push EOF onto the stream using ungetc is ignored. The
ungetc function returns an error value if nothing has yet been read from stream or if c can­
not be pushed back.

Characters placed on the stream by ungetc may be erased if mush, fseek, fsetpos, or
rewind is called before the character is read from the stream. The file-position indicator
will have the same value it had before the characters were pushed back. On a successful
ungetc call against a text stream, the file-position indicator is unspecified until all the
pushed-back characters are read or discarded. On each successful ungetc call against a bi­
nary stream, the file-position indicator is stepped down; if its value was 0 before a call, the
value is undefined after the call.

Results are unpredictable if the ungetc function is called twice without a read operation be­
tween the two calls. After a call to the fscanf function, a call to ungetc may fail unless
another read operation (such as the getc function) has been performed. This is because the
fscanf function itself calls the ungetc function.

Return Value The ungetc function returns the character argument c. The return value EOF indicates a
failure to push back the specified character.

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

See Also getc, getchar, putc, putchar

I * U N GETC . C : T h i s p r o g r a m f i rs t c o n v e r t s a c h a r a c t e r r e p r e s e n t a t i on of a n
* u n s i g n ed i n t e g e r t o a n i n tege r . I f t h e p r o g r a m e n c o u n t e r s a c h a r a c t e r
* t h a t i s n o t a d i g i t , t h e p r og r a m u s e s u n g e t c t o repl a c e i t i n t h e s t ream .
*I
ungetc 806

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


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

v o i d ma i n ( )
(
i nt c h ;
i nt resul t - 0 ;

p r i n t f C " En t e r a n i n te.ge r : • ) ;

I * Rea d i n a nd c o n v e rt n umbe r : * /
w h i l e ( C C c h - g e t c h a r ( ) ) I • EO F > && i s d i g i t ( c h > >
r e s u l t - re s u l t * 1 0 + c h - ' 0 ' ; / * U s e d i g i t . */
i f ( c h I• E O F )
ungetc C c h , s td i n ) ; / * Put n o n - d i g i t ba c k . * /
p r i n t f ( " N umber = %d \ n N ext c h a r a c t e r i n s t r e a m = ' %c ' \ n " ,
r e s u l t , g et c h a r C > ) ;

Output

Enter a n i nteger : 52la


N umber = 5 2 1
N e x t c h a r a c t e r i n s t ream a 'a'
807 ungetch

DalJllptlan Pushes back the last character read from the console.

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

int ungetch( int c );

c Character to be pushed

R1111adtl The ungetch function pushes the character c back to the console, causing c to be the next
character read by getch or getche. The ungetch function fails if it is called more than once
before the next read. The c argument may not be EOF.

R""'m .Value The ungetch function returns the character c if it is successful. A return value of EOF indi­
cates an error.

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

S1111 Alla cscanf, getch, getche

I * U N G ETCH . C : I n t h i s p rog ram , a w h i t e - s p a c e d e l i mi t ed t o k e n i s r e a d


* from t h e keyboa rd . When t h e p r o g r a m e n c o u n t e r s a d e l i m i t e r ,
* i t u s e s u n g e t c h t o repl a c e t h e c h a ra c t e r i n t h e keyboa rd buffe r .
*I

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

voi d ma i n ( )
(
c h a r buffe r [ 100 ] ;
i n t count - 0 ;
i nt ch ;
ungetch 808

c h = getche C l :
whi l e ( i sspace ( ch > / * S k i p p r e c ed i n g w h i t e s p a c e . * /
ch = getche C > :
whi l e ( count < 99 ) I* Gather token . */
(
i f ( i sspace C ch > I * End o f t o k e n . * /
brea k :
buffe r [ c o u n t++] = c h :
c h = g e t c he C l :
)
ungetch ( c h > : I * Put ba c k d e l i mi t e r . * /
buffe r [ c o u n t ] = ' \ 0 ' : / * N u l l t e rmi n a t e t h e t o k e n . * /
pri ntf( " \ ntoken = %s\n " , buffer > :

Output

W h i te
token = W h i t e
809 unlink

Dest:r/pllan Deletes a file.

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


#include <Stdio.h> Use either IO.H or STDIO.H

int unlink( const char *filename );

filename Name of file to remove

.Remat1cs The unlink function deletes the file specified by filename.

Retum Value If successful, unlink returns O; otherwise, it returns -1 and sets ermo to one of the follow­
ing constants:

Value Meaning

EACCES Path name specifies a read-only file


ENOENT File or path name not found, or path name specified a directory

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

See Also close, remove

/ * U N L I N K . C : T h i s p r o g r a m u s e s u n l i n k t o del ete U N L I N K . OBJ . * /

#i ncl ude <stdi o . h>

v o i d ma i n ( )
{
i f ( u n l i n k ( " u n l i n k . obj " ) � -1 )
p e r ro r C " Co u l d n o t d e l ete ' U N L I N K . O BJ ' " > :
el se
p r i n t f C " De l eted ' U N L I N K . OBJ ' \ n " ) ;

Output

D e l eted ' U N L I N K . O BJ '


_unregisterfonts 810

Dat:rlptlan Frees memory used by fonts.

#include <graph.h>

void _far _unregisterfonts( void );

Remarks The _unregisterfonts function frees memory previously allocated and used by the
_registerfonts function. The _unregisterfonts function removes the header information
for all fonts and unloads the currently selected font data from memory.
Any attempt to use the _setfont or _outgtext function after calling _unregisterfonts re­
sults in an error.

Return Value None.

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

See Also _getfontinfo, _getgtextextent, _outgtext, _registerfonts, _setfont

Example See the example for _outgtext.


811 utime

DBScrlpllan Sets the file modification time.

#include <Sys\types.h>
#include <Sys\u�me.h>

int utime( char *filename, struct utimbuf *times );

filename File name


times Pointer to stored time values

Remarks The utime function sets the modification time for the file specified by filename. The
process must have write access to the file; otherwise, the time cannot be changed.

Although the utimbuf structure contains a field for access time, only the modification time
is set under DOS and OS/2 . If times is a NULL pointer, the modification time is set to the
current time. Otherwise, times must point to a structure of type utimbuf, defined in
SYS\UTIME.H. The modification time is set from the modtime field in this structure.

Return Value The utime function returns the value 0 if the file-modification time was changed. A return
value of -1 indicates an error, and errno is set to one of the following values:

Value Meaning
EACCES Path name specifies directory or read-only file

EINVAL Invalid argument; the times argument is invalid


EMFILE Too many open files (the file must be opened to change its
modification time)

ENOENT File or path name not found

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

BBB Also asctime, ctime, fstat, ftime, gmtime, localtime, stat, time

I * U T I M E . C : T h i s p r o g r a m u s e s ut i me to s et t h e f i l e-mod i f i c a t i on t i me t o
* t h e c u r r e n t t i me .
*I
uli111e 812

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


#i n c l u d e <stdl i b . h>
#i n c l ude < s y s \ types . h >
#i n c l ude < sy s \ u t i me . h >

v o i d ma i n ( )
{
I * S h ow fi l e t i me before a n d a ft e r . * /
s y s t e m ( " d i r ut i me . c " ) ;
i f ( u t i me C " u t i me . c " , N U L L ) == -1 )
p e r ro r C " u t i me fa i l ed \ n " ) ;
el se
p r i n t f ( " F i l e t i me mod i f i ed \ n " ) ;
s y s t e m ( " d i r u t i me . c " ) ;

Output

T h e vol ume l a bel i n d r i v e C i s OS2 .


D i r e c t o ry of C : \ L I B R E F

UT I M E C 397 6 - 20-89 2 : 11p


1 Fi l e ( s ) 1 2 9 7 4080 byt e s f re e
F i l e t i me mod i f i ed

T h e vol ume l a b e l i n d r i v e C i s OS2 .


D i r e c t o ry of C : \ L I B R E F

UT I M E C 397 6 - 20-89 2 : 12p


1 Fi l e C s > 1 2 9 74080 byt e s f r e e
813 va_arg, va_end, va_start

Description Access variable-argument lists.

#include <Stdarg.h> Required for ANSI compatibility


#include <Varargs.b> Required for UNIX V compatibility
#include <Stdio.h>

type va_arg( va_list arg_ptr, type );


void va_end( va_list arg_ptr );
void va_start( va_list arg_ptr ); UNIX version
void va_start( va_Iist arg_ptr, prev_param ); ANSI

arg_ptr Pointer to list of arguments


prev_param Parameter preceding first optional argument (ANSI only)
type TYpe of argument to be retrieved

Remarks The va_arg, va_end, and va_start macros provide a portable way to access the arguments
to .a function when the function talces a variable number of arguments. Two versions of the
macros are available: the macros defined in STDARG.H confonn to the proposed ANSI C
standard, and the macros defined in VARARGS.H are compatible with the UNIX System
V definition. The macros are listed below:

Macro Description

va_alist Name of parameter to called function (UNIX version only)


· va_arg Macro to retrieve current argument
va dcl Declaration of va alist (UNIX version only)
va end Macro to reset arg_ptr
va_list The typedef for the pointer to list of arguments
va_start Macro to set arg_ptr to beginning of list of optional argu­
ments (UNIX version only)

Both versions of the macros assume that the function talces a fixed number of required ar­
guments, followed by a variable number of optional arguments. The required arguments
are declared as ordinary parameters to the function and can be accessed through the param­
eter names. The optional arguments are accessed through the macros in STDARG.H or
VARARGS.H, which set a pointer to the first optional argument in the argument list,
va_arg, va_end, va_start 814

retrieve arguments from the list, and reset the pointer when argument processing is
completed.

The proposed ANSI C standard macros, defined in STDARG.H, are used as follows:

1 . All required arguments to the function are declared as parameters in the usual way. The
va_dcl macro is not used with the STDARG.H macros.
2. The va_start macro sets arg_ytr to the first optional argument in the list of arguments
passed to the function. The argument arg_ytr must have va_list type. The argument
prev_yaram is the name of the required parameter immediately preceding the first
optional argument in the argument list. If prev_yaram is declared with the register
storage class, the macro's behavior is undefined The va_start macro must be used
before va_arg is used for the first time.
3. The va_arg macro does the following:
• Retrieves a value of type from the location given by arg_ytr
• Increments argytr to point to the next argument in the list, using the size of type to
determine where the next argument starts
The va_arg macro can be used any number of times within the function to retrieve ar­
guments from the list.

4. After all arguments have been retrieved, va_end resets the pointer to NULL.

The UNIX System V macros, defined in VARARGS.H, operate in a slightly different man­
ner, as follows:

1 . Any required arguments to the function can be declared as parameters in the usual way.
2. The last (or only) parameter to the function represents the list of optional arguments.
This parameter must be named va_alist (not to be confused with va_Iist, which is de­
fined as the type of va_alist).

3. The va_dcl macro appears after the function definition and before the opening left
brace of the function. This macro is defined as a complete declaration of the va_alist
parameter, including the terminating semicolon; therefore, no semicolon should follow
va_dcl.
4. Within the function, the va_start macro sets argytr to the beginning of the list of op­
tional arguments passed to the function. The va_start macro must be used before
va_arg is used for the first time. The argument arg_ytr must have va_list type.
5. The va_arg macro does the following:
• Retrieves a value of type from the location given by argytr
• Increments arg_ytr to point to the next argument in the list, using the size of type to
determine where the next argument starts
815 va_arg, va_end, va_start

The va_arg macro can be used any number of times within the function to retrieve the
arguments from the list.

6. After all arguments have been retrieved, va_end resets the pointer to NULL.

R""m Va/us The va_arg macro returns the current argument; va_start and va_end do not return values.

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

S11 Alsa vfprintf, vprintf, vsprintf

I * VA . C : The p r o g r a m bel ow i l l u s t r a t e s pa s s i n g a v a r i a b l e n umber of a rg umen t s


* u s i n g t h e fol l ow i ng ma c ro s :
* va_s t a r t v a_a rg v a_end
* va_l i s t va_d e c l ( U N I X o n l y )
*I

#i n c l u d e < s t d i o . h >
lld e f i n e ANS I / � C ommen t o u t f o r U N I X v e r s i on *I
Ii i fdef A N S I I * AN S I c ompa t i b l e v e r s i on *I
#i n c l u d e < s td a r g . h>
i nt a v e ra g e ( i n t f i r s t , ... );
llel s e I * U N I X c ompa t i b l e v e r s i o n *I
#i n c l u d e < v a ra r g s . h >
i nt a v e r a g e ( v a_l i s t ) ;
/le n d i f

v o i d ma i n ( )
{
I * C a l l w i t h 3 i nt e g e r s C - 1 i s u s ed a s t e rm i n a t o r ) . * /
p r i n t f ( " A v e r a g e i s : % d \ n " , a ve r a g e ( 2 , 3 , 4 , - 1 ) ) ;

I * C a l l w i t h 4 i nt e g e r s . * /
p r i n t f ( " Av e r a g e i s : % d \ n " , a v e r a g e ( 5 , 7 , 9 , 1 1 , - 1 > > ;

I * C a l l w i t h j u s t - 1 t e rmi n a t o r . * /
p r i n t f ( " Av e r a g e i s : % d \ n " , a v e r a ge ( - 1 > > ;

I * Ret u r n s t h e a v e ra g e o f a v a ri a b l e l i s t o f i n t e g e r s . * /
#i fdef A N S I / * A N S I c ompa t i b l e v e r s i on */
i n t a v e r a g e ( i nt f i r s t , >
{
. . •

i n t c o u n t = 0 , s um = 0 , i = f i r s t ;
v a_l i s t ma r k e r ;
va_arg, va_end, va_start a16

v a_s t a rt ( ma r k e r , f i r s t > : / * I n i t i a l i ze v a r i a bl e a rg umen t s . * /


whi l e ( i ! = . -1 )
{
s u m += i ;
c o u n t++ ;
i = va_a rg ( ma r k e r , i n t ) ;

v a_en d ( ma r k e r ) ; / * Reset v a r i a b l e a rg umen t s . */


retu rn ( s um ? ( s um I c o u n t ) : 0 ) ;
)
#el s e / * U N I X c ompa t i b l e v e r s i on m u s t u s e ol d - styl e d e f i n i t i on . * /
i nt a v e ra g e < va_a l i s t )
va_d c l
{
i n t i , c o u n t , s um ;
v a_l i s t ma r k e r ;

v a_s t a rt ( ma r k e r l ; / * I n i t i a l i ze v a r i a b l e a rgument s . * /
f o r ( s um = c o u n t = 0 ; ( i = v a_a rg ( ma r k e r , i n t ) ) ! = - 1 ; c o u n t++ )
s um += i ;
va_end ( ma r k e r ) ; / * Re s e t v a r i a bl e a rg umen t s . */
ret u r n < s um ? < s um I c o u n t ) 0 );
)
/len d i f

Output

Average i s : 3
Average i s : 8
Average i s : 0
817 vfprintf, vprintf, vsprintf

Description Write fonnatted output using a pointer to a list of arguments.

#include <Stdio.h>
#include <varargs.h> Required for compatibility with UNIX System V

#include <Stdarg.h> Required for compatibility with the ANSI C standard

int vfprintf( FILE *stream, const char *format, va_list argptr );


int vprintf( const char *format, va_list argptr );
int vsprintf( char *buffer, const char *format, va_list argptr );

stream Pointer to FILE structure


format Fonnat control
argptr Pointer to list of arguments
buffer Storage location for output

Remarks The vfprintf, vprintf, and vsprintf functions format data and output data to the file
specified by stream, to standard output, and to the memory pointed to by buffer, respective­
ly. These functions are similar to their counterparts fprintf, printf, and sprintf, but each
accepts a pointer to a list of arguments instead of an argument list.
Theformat argument has the same fonn and function as theformat argument for the printf
function; see printf for a description offormat.

The argptr parameter has type va_list, which is defined in the include files VARARGS.H
and STDARG.H. The argptr parameter points to a list of arguments that are converted and
output according to the corresponding fonnat specifications in the fonnat.

Return Value The return value for vprintf and vsprintf is the number of characters written, not counting
the tenninating null character. If successful, the vfprintf return value is the number of
characters written. If an output error occurs, it is a negative value.

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


vlprintf, vprintl, vsprintf 818

SBB Also fprintf, printf, sprintf, va_arg, va_end, va_start

/ * V P R I N T F . C s h ows h ow t o u s e v p r i n t f f u n ct i o n s t o w r i t e n ew v e r s i o n s
* o f p r i n t f . T h e v s p r i n t f f u n c t i on i s u s e d i n t h e exampl e .
*/

#i n c l u d e <stdi o . h>
#i n c l u d e <graph . h>
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s td a rg . h>
#i n c l u d e <ma l l oc . h >

i nt wp r i n t f ( s h o r t r ow , s h ort c o l , s h o r t c l r , l on g b c l r , c h a r * fmt , • . • >;

v o i d ma i n ( )
(
s h o rt fgd .. 0 ;
l on g bgd .. 0 L ;

_c l e a r s c reen ( _GC LEARSC R E E N ) ;


_outtext C " Co l o r text exampl e : \ n \ n " > ;

I * Loop t h r o u g h 8 b a c k g ro u n d c o l o rs . * /
fo r ( b g d = 0 L ; b g d < 8 ; bgd++ >
(
wp r i n t f ( C i n t ) bgd · + 3 , 1 , 7 , bgd , " Ba c k : %d Fo re : " , bgd ) ;

/ * 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 ( fgd = 0 ; fgd < 1 6 ; fgd++ >
wp r i n t f ( - 1 , - 1 , fgd , - l L , • % 2 d • , fgd ) ;

/ * Ful l - s c reen wi n d ow v e r s i on of p r i n t f t h a t ta kes row , c o l umn , t e x t c o l o r ,


* a n d ba c kg round c o l o r a s i t s f i r s t a rg ument s , f o l l owed by n o rma l p r i n t f
* fo rma t s t r i n g s ( except t h a t \ t i s not h a n d l ed ) . Y o u c a n s pec i fy - 1 f o r
* a ny o f t h e f i r s t a rguments t o u s e t h e c u r rent v a l ue . T h e f u n c t i on ret u r n s
* t h e n umber of c h a r a c t e r s p r i n t e d , o r a n e g a t i v e n umber f o r e r r o r s .
*I
i n t wp r i n t f C s h o r t r ow , s h o r t c o l , s ho rt c l r , l on g b c l r , c h a r *fmt , • . .

(
s t r u c t r c c o o r d tmppo s ;
s hort ret , s i z e ;
v a_l i s t ma r k e r ;
cha r *buffe r ;
819 vtprintf, vprintf, vsprintf

I * I t ' s p r o ba bl y s a fe t o u s e a buffe r l en g t h of 5 1 2 by tes o r f i v e t i me s


* t h e l en g t h of t h e fo rma t s t r i n g .
*/
s i z e = s t r l en ( fmt ) ;
s i ze m ( s i ze > 5 1 2 ) ? 5 1 2 : s i ze * 5 ;
i f ( ( buffer = ( c h a r * ) ma l l oc ( s i z e > > == N U L L )
return - 1 ;

I * Set text p os i t i on . * /
tmppos - _g ettextpo s i t i on ( ) ;
i f ( row < 1 )
row = tmppos . row ;
i f ( co1 < 1 )
c o l - tmppos . c ol ;
_s ettextpos i t i on ( row , c o l > ;

I * Set f o r e g r o u n d a n d b a c k g round c o l o r s . * /
i f ( c l r >= Ill )
_s ett e x t c o l o r ( c l r ) ;
i f C be 1 r >· Ill )
_s etb k c o l o r ( b c l r ) ;

I * W r i te text to a s t r i n g a n d output t h e s t r i n g . */
va_s ta rt ( ma r k e r , fmt ) ;
ret = v s p r i n t f ( buffe r , fmt , ma r k e r ) ;
v a_en d ( ma r k e r > ;
_ou t t ext ( b u f f e r ) ;
f r e e ( buffer ) ;
r e t u r n ret ;
wait 820

D11scrlpUan Suspends the calling process.

#include <process.h>

int wait( int *termstat );

termstat Tennination-status word and return code for tenninated child


process

R11matks The wait function suspends the calling process until any of the caller's immediate child
processes tenninate. If all of the caller's children have tenninated before it calls the wait
function, the function returns immediately.
If not NULL, termstat points to a buffer containing a tennination-status word and return
code for the child process. The status word indicates whether or not the child process
ended nonnally by calling the OS/2 DosExit function. Supply NULL if you do not need
the child's tennination-status word.

If the child process did tenninate nonnally, the low-order and high-order bytes of the
tennination-status word are as follows:

Byte Contents

Low order 0
High order Low-order byte of the result code passed by the child process
to DosExit. The DosExit function is called if the child
process c alled exit or _exit, if it returned from main, or if it
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.

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

If the child process tenninated for any other reason, the high-order and low-order bytes of
the tennination-status word are as follows:

Byte Contents
Low order Tennination code from DosWait:

Code Meaning
1 Hard-error abort

2 Trap operation

3 SIGTERM signal not


intercepted
High order 0

Return Value If wait returns after nonnal tennination of a child process, it returns the child's process ID.
If wait returns after abnonnal tennination of a child process, it returns the number -1 and
sets ermo to EINTR.

Otherwise, wait returns -1 immediately and sets ermo to ECHILD, indicating that no
child processes exist for the calling process.

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

See Also cwait, exit, _exit

/ * WA I T . C : T h i s p r o g r a m l a un c h e s s ev e r a l c h i l d p r o c e s s e s a nd wa i t s for
* the f i r s t t o f i n i s h .
*I

#d e f i n e I N C L_NO P M
#d e f i n e I N C L_NOCOMMON
#d e f i n e I N C L_DO S P RO C E S S
#i n c l u d e < o s 2 . h > / * D o s S l eep */
#i n c l u d e < p ro c e s s . h > / * wa i t */
#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 >
#i n c l u d e < t i me . h >
wait 822

I * M a c r o t o get a r a n d om i n t e g e r w i t h i n a s p ec i f i ed r a n g e */
#d ef i n e g e t r a ndom C mi n , max > C C ra nd C l % C i nt > C C C ma x ) + 1 ) C mi n ) ) ) + ( mi n ) )
-

s t ruct C H I LD
(
i nt pi d ;
cha r n a me [ l 0 J ;
c h i l d [ 4 ] = ( ( 0 , " An n • J , ( 0 , " Be t h " J , ( 0 , " C a r l • J , ( 0 , " Da v e • J J ;

v o i d ma i n ( i n t a r g c , c h a r *a rg v [ J
(
i nt t e rms t a t , p i d , c , tmp ;

s ra n d C C u n s i gned ) t i me C N U L L ) > : I * Seed r a n d omi z e r * /


I * I f n o a rgumen t s , t h i s i s t h e pa rent . * /
i f ( a rgc =- 1 >
(

I * Spawn c h i l d r en i n ra ndom o r d e r w i t h a r a n d om d e l ay . * /
t m p = get r a n d o m C 0 , 3 > :
fo r e c = tmp ; c < tmp + 4 ; c++ >
chi l d[c % 4] .pid s p a w n l C P_N DWA I T , a rg v [ 0 ] , a rg v ( 0 ] ,
=

c h i l d [ c % 4 ] . n ame , N U L L > :

I * Wa i t f o r t h e f i r s t c h i l d ren . O n l y get I D of f i r s t . * /
p r i n t f C " W h o ' s f i rs t ? \ n " > :
p i d = wa i t ( & t e rm s t a t > :
fo r ( c = 0 ; c < 3 ; c++ )
wa i t ( & t e rms t a t > :

I * C h e c k I D s t o s ee w h o wa s fi r s t . * /
fo r ( c - 0 ; c < 4 ; c++ )
i f ( pi d =- chi l d[cJ .pid >
p r i n t f C " %s wa s fi r s t \ n \ n " , c h i l d [ c J . n ame > :

I * I f t h e r e a re a rg ument s , t h i s must be a c h i l d . * /
el s e
(
/ * Del ay f o r r a n d om t i me . * /
s ra n d C C u n s i g n ed ) t i me C N U L L > * a rg v [ l ] [0 J > :
Dos S l eep C g e t r a n d o m C l , 5 ) * 1000L > :
p r i n t f C " H i , d a d . I t ' s % s . \ n " , a rg v [ l ] > :
823 wait

Output

Who ' s fi rst?


Hi , dad . I t • s Carl .
H i , d a d . I t ' s Ann .
H i , d a d . I t ' s Bet h .
Hi , dad . I t ' s Dave .
C a r l wa s f i r s t
_wrapan 824

Dest:r/pUan Controls word wrap.

#include <graph.h>

short .Jar ._wrapon( short option );

option Wrap condition

Remades The _wrapon function controls whether text output with the _outtext function wraps to a
new line or is simply clipped when the text output reaches the edge of the defined text win­
dow. The option argument can be one of the following manifest constants:

Constant Meaning
_GWRAPOFF Truncates lines at window border

_GWRAPON Wraps lines at window border

Note that this function does not affect the output of presentation-graphics routines or font
routines.

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

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

See Also _outtext, _settextwindow

Examp• ��������---
1 * W RAPON . C * /

#i n c l u d e < c o n i o . h >
#i n c l u d e < g r a p h . h >

v o i d ma i n ( )
{
_w r a pon ( _GW RA P O N ) ;
w h i l e ( ! kb h i t ( ) )
_out t e x t < " W r a p o n ! • );
getc h ( ) ;
_o uttext '< " \ n \ n " ) ;

w r a p o 7 < GWRA P O F F ) ;
w h i l e < , ! kb h i t ( ) >
I
12s _wrapon

outtex t ( " W r a p o f f !
_ • );
getc h ( l ;
_outtext ( " \ n \ n " ) ;

Output

W r a p o n ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! Wra p on ! Wra p on ! W r a p
on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on !
W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W ra p on ! W r
a p on ! Wra p on ! Wra p on ! Wra p on ! W r a p on ! W r a p on ! W r a p on ! W r a p o
n ! W r a p on ! W r a p on !

W ra p o f f ! W r a p off ! W r a p o f f ! W r a p o f f ! W r a p off ! Wra p off ! Wra p off ! W r a p


write 826

Description Writes data to a file.

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

int write( int handle, void *buffer, unsigned int count );

handle Handle referring to open file

buffer Data to be written

count Number of bytes

Remadrs The write function writes count bytes from buffer into the file associated with handle. The
write operation begins at the current position of the file pointer (if any) associated with the
given file. If the file is open for appending, the operation begins at the current end of the
file. After the write operation, the file pointer is increased by the number of bytes actually
written.

Retum Value The write function returns the number of bytes actually written. The return value may be
positive but less than count (for example, when write runs out of disk space before count
bytes are written).
A return value of 1 indicates an error. In this case, errno is set to one of the following
-

values:

Value Meaning

EBADF Invalid file handle or file not opened for writing

ENOSPC No space left on device

If you are writing more than 32K (the maximum size for type int) to a file, the return value
should be of type unsigned int. (See the example that follows.) However, the maximum
number of bytes that can be written to a file at one time is 65,534, since 65,535 (or
OxFFFF) is indistinguishable from -1 and would return an error.
If the file is opened in text mode, each line-feed character is replaced with a carriage­
return-line-feed pair in the output. The replacement does not affect the return value.
When writing to files opened in text mode, the write function treats a CTRL+Z character as
the logical end-of-file. When writing to a device, write treats a CTRL+Z character in the
buffer as an output terminator.
827 write

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

See Also fwrite, open, read

I * W R I T E . C : T h i s p r o g r a m opens a f i l e f o r output a nd u s e s w r i te t o
* w r i te s ome b y t e s to t h e f i l e .
*I

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


#i n c l u d e <stdi o . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e <fcntl . h>
#i n c l u d e < sy s \ ty p e s . h >
#i n c l u d e < s y s \ s ta t . h >

c h a r buffer [ ] = " Th i s i s a t e s t of ' w r i te ' f u n c t i on " ;

v o i d ma i n ( )
(
i nt fh ;
u n s i gned byt e sw r i tten ;

i f { ( f h = open ( " w r i t e . a " , O_RDWR I O_C R EAT , S_I READ I S_I W R I T E l l ! = - 1


(
i f { ( by t e s w r i tten = w r i t e ( fh , buff er , s i zeof ( buffer ) l l == - 1 )
p e r r o r ( " W ri te fa i l ed " ) ;
el se
p r i n t f ( " W rote %u bytes to f i l e \ n " , byt eswr i t ten l ;

c l os e < f h l ;

Output

Wrote 3 5 byt e s to fi l e
Index
A jOj l jn, 1 07
jOl,j l l ,jnl, 1 07
abort, 5 1 , 76 yO,y l ,yn, 1 07
abs, 78 _yOl,_y l l ,_ynl, 1 07
Absol ute value _bexpand, 260
abs, 78 _bfree, 3 1 0
cabs, 1 34 _bfreeseg, 1 1 0
cabsl, 1 34 _bheapadd, 406
fabs, 263 _bheapchk, 409
fabsl, 263 _bheapmin, 4 1 1
labs, 44 1 _bheapseg, 1 1 2
access, 24, 80 _bheapset, 4 1 2
·Access 1node, 269, 295, 3 1 5, 326 _bheapwalk, 4 1 5
acos, 46, 82 B inary
acosl, 46, 82 fonnat, conversion to IEEE
alloca, 48, 84 double precision, 1 8 1
Allocation. See Memory allocation int
_amblksiz variable, 63 reading, 389
Appending writing, 597
constants, 523, 704 mode
streams, 295 , 3 1 5 , 326 _fmode, 66
_arc, _arc_w, _arc_wxy fdopen, 269
description, 86 fopen, 296
use, 30 freopen, 3 1 5-3 1 6
Arccosine function, 82 _fsopen, 327
Arcsine function, 90 open, 523
Arctangent function, 94 setmode, 664
Arguments sopen, 704
singularity, 480 vs. text mode, 35
type checking, vi search, 1 32, 447, 466
variable-length number, 62, 8 1 7 BINMODE.OBJ, 66
asctime, 60, 88 _bios_disk, 57, 1 1 5
asin, 46, 90 _bios_equipl ist, 57, 1 1 9
asinl , 46, 90 _bios_keybrd, 57, 1 2 1
assert, 92 _bios_memsize, 57, 1 24
Assertions, 92 _bios_printer, 57, 1 25
atan, atan2, 46, 94 _bios_serialcom, 57, 1 27
atanl, atan21, 46, 94 _bios_timeofday, 57, 1 30
atexit, 5 1 , 96 _bmalloc, 476
atof, atoi, atol, _atold, 22, 98 _bmsize, 5 1 9
Attributes, 29 Bold type, use of, ix

8
Brackets, double, use of, ix
_brealloc, 607
bsearch, 55, 1 32
_bcal loc, 1 3 6 B uffer manipulation
bdos, 5 7 , I O I _fmemccpy, 487
_beginthread, I 03 _fmemchr, 489
Bessel functions _fmemcmp, 49 1
/ described, 48, 1 07 _fmemcpy, 494

829
830 Microsoft C Run-Time Library Reference

B uffer mani p ul ation (co11ti1111ed) isspace, 2 1 , 434


_fmemicm p , 497 isupper, 2 1
_fmemmove, 50 1 isxdigit, 2 1 , 434
_fmemset, 504 toascii, 2 1 , 796
memccpy, 487 tolower, _tolower, 2 1 , 796
memchr, 489 toupper, _toupper, 2 1 , 796
memcmp, 49 1 Characters
memcpy, 494 converting. See Character classification and
memicm p , 497 conversion functions
memmove, 50 I dev ice, 437
memset, 504 reading
B uffering fgetc, fgetchar, 278
described, 37 from console, 348
preopened streams, 40 from port, 425
using, 40 getc, getchar, 346
B uffers read function, 605
assigning, 648 ungetting, 805, 807
comparing, 49 1 , 497 writing
copying, 487, 494 fputc, fp utchar, 305
flushing, 276, 292 p utc, p utchar, 589
searching, 489 to console, 59 1
setting characters, 504 to port, 532
B UFSIZ constant, 37 write function, 826
Byte order, swapp ing, 783 chdir, 23 , 1 45
_chdrive, 1 47

c Child process
cw a it
cabs, 46, 1 34 s ignal settings, 707
cabsl, 46, 1 34 termination-status word, 1 77, 707, 820
calloc, 48, 1 36 exec, 25 1
Carry flag floating-point state of p arent, 300
bdos, 1 0 1 s pawn, 707
int86, 426 wait, 820
int86x, 428 chmod, 24, 1 49
intdos, 430 chsize, 24, 1 5 1
intdosx, 432 _clear87, 46, 1 53
Case in file names, 9 clearerr, 37, 1 5 5
cei l , 46, 1 38 _clearscreen, 29, 1 57
Ceil ing function, 1 38 C l i pp ing regions, 650
ceil l , 46, 1 38 clock, 60, 1 59
_cexit, _c_exit, 1 40 clock_t type, 68
cgets, 44, 1 4 1 close, 42, 1 6 1
_chain_intr, 57, 60, 1 43 Comp arison
Character classification and conversion functions max macro, 484
include files, 22 min macro, 506
isalnum, 2 1 , 434 Compatibility mode, 704
iscntrl , 434 com p lex ty pe, 68
isdigit, 434 CONIO.H, 44
isgraph, 434 Console, ungetting characters from, 807
islower, 2 1 , 434 _control87, 46, 1 63
isprint, 2 1 , 434
ispunct, 2 1 , 434
Index 831

Conversion dieeetomsbin, dmsbintoieee, 46, 1 8 1


characters. See Character classification and conversion difftime, 6 1 , 1 82
functions DIRECT.ff, 23
data. See Data conversion Directories
floating-point numbers creating, 507
IEEE double to M S binary double, 1 8 1 deleting, 624
to integers and fractions, 5 1 3 getting current, 354, 356
to strings, 243, 267, 340 renaming, 620
integers to strings, 438 Directory control
long integers to strings, 47 1 , 80 1 chdir, 23
strings to chmod, 1 49
floating-point values, 98 getcwd, 23, 354
lowercase, 750 _getdcwd, 356
uppercase, 780 include files, 23
time. See Time, conversion mkdir, 23, 507
cos, cosh, 46, 1 66 remove, 6 1 9
Cosine, 1 66 rmdir, 23
cos!, coshl, 46 unlink, 809
cprintf, 8, 44, 1 68 _disable, 57, 60, 1 84
cputs, 44, 1 70 diskfree_t structure, 69
creat, 42, 1 7 1 diskinfo_t structure, 69
cscanf, 8 , 44 , 1 73 _displaycursor, 1 85
ctime, 60, 1 75 div, 1 87
CTYPE.H routines, 22, 434 div_t type, 69
cwait, 1 77 Division
div, 1 87
0 ldiv, 445
Document conventions, ix
Data conversion DOMAIN, 480
See also Conversion DOS commands, execution within programs, 784
atof, atoi, atol, _atold, 22, 98 DOS error codes, 65
ecvt, 22, 243 DOS interface routines
fcvt, 22, 267 bdos, 57, 1 0 1
gcvt, 22, 340 _bios_disk, 1 1 5
include files, 22 _bios_equiplist, 1 1 9
itoa, 22, 438 _bios_keybrd, 1 2 1
ltoa, 22, 47 1 _bios_memsize, 1 24
strtod, strtol, strtoul, 22, 775 _bios_printer, 1 25
ultoa, 23 , 80 1 _bios_timeofday, 1 30
Data items _chain_intr, 1 43
reading, 308 _disable, 1 84
writing, 338 _dos_allocmem, 1 89
Date routines. See Time, routines _dos_close, 1 9 1
Daylight variable, 64, 799 _dos_creat, _dos_creatnew, 1 93
Default translation mode _dos_findnext, 1 95
child process, used in, 707 _dos_freemem, 1 98
_fmode, 66 _dos_getdate, 200
_fopen, 296 _dos_getdiskfree, 202
_fsopen, 327 _dos_getdrive, 204
O_TEXT, 523 _dos_getfileattr, 206
setmode, 664 _dos_getftime, 208
sopen, 704 _dos_gettime, 2 1 1
832 Microsoft C Run-Time Library Reference

DOS interface routines (collfi1111ed) _dos_setblock, 58, 22 l


_dos_getvect, 2 1 3 _dos_setdate, 58, 223
_dos_keep, 2 1 4 _dos_setdrive, 58, 225
_dos_open, 2 1 6 _dos_setfileattr, 58, 227
_dos_read, 2 1 9 _dos_setftime, 58, 229
_dos_setblock, 22 l _dos_settime, 59, 232
_dos_setdate, 223 _dos_setvect, 59, 234
_dos_setdrive, 225 _dos_write, 59, 237
_dos_setfileattr, 227 Drive routines
_dos_setftime, 229 _chdrive, 147
_dos_settime, 232 _getdrive, 359
_dos_setvect, 234 dup, dup2, 42, 24 l
_dos_write, 237 Dynamic allocation. See Memory allocation
dosexterr, 239
_enable, 59, 247 E
FP_OFF, 59
harderr, _hardresume, _hardretn, 59 E2B IG, 66
include files, 57 EACCES, 66
int86, 59, 426 EBADF, 66, 826
int86x, 428 ecvt, 22, 243
intdos, 59, 430 EDEADLOCK, 66
intdosx, 432 EDOM, 66
segread, 59, 640 EEXIST, 66
and uses (l ist), 57 EINVAL, 66
DOS interrupts, invoking, 426, 428 _el lipse, _ellipse_w ,_ellipse_wxy, 30, 245
DOS system calls Ellipses, x
_bios_serialcom, 1 27 EMFILE, 66
error handl ing, 239 _enable, 59, 247
invoking, lO l , 430, 432 End-of-file
DOS version number, detection, 67 indicators, 1 55
DOS.H, 57 low-level 1/0, 249
_dos_al locmem, 57, 1 89 stream 1/0
_dos_close, 57, 1 9 1 clearing, 1 55, 622
_dos_creat, 57, 1 93 described, 272
_dos_creatnew, 58, 1 93 _endthread, 248
dosdate_t structure, dostime_t structure, 69 ENOENT, 66
_dosermovariable, 65 ENOEXEC, 66
DOSERROR type, 69, 239 ENOMEM, 66
dosexterr, 59, 239 ENOSPC, 66, 826
_dos_findfirst, 58, 1 95 environ variable, 67-68, 360, 592
_dos_findnext, 58, 1 95 Environment variables
_dos_freemem, 58, 1 98 described, 68
_dos_getdate, 58, 200 getenv, 360
_dos_getdiskfree, 58, 202 putenv, 592
_dos_getdrive, 58, 204 eof, 42, 249
_dos_getfileattr, 58, 206 EOF constant, 37
_dos_getftime, 58, 208 ERANGE, 66
_dos_gettime, 58, 2 1 1 ermo variable
_dos_getvect, 58, 2 1 3 and perror, strerror, 1 3
_dos_keep, 58, 2 1 4 described, 65
_dos_open, 58, 2 1 6 error numbers, 538, 742
_dos_read, 58, 2 1 9
Index 833

ermo variable (continued) fgetc, fgetchar, 37, 278


graphics, routines, 1 3 fgetpos, 37, 280
1/0 routines, 1 3, 43 fgets, 37, 282
math routines, 1 3 _tbeapchk, 48, 409
Error handling _tbeapmin, 4 1 1
DOS error codes, 65 _tbeapset, 49, 4 1 2
DOS system calls, 239 _tbeapwalk, 49, 4 1 5
logic errors, 92 fieeetomsbin, fmsbintoieee, 47
perror, 1 3, 538 FILE
strerror, _strerror, 13, 742 pointer, 37
Error indicator structure, 37
described, 4 1 , 1 5 5 type, 69
ferror, 274 File handles
return value, 1 3 duplication, 24 1
Error messages, user supplied, 538, 742 functions, 42
Euclidean distance, 42 1 predefined, 43
exception type, 69, 480 stream, 287
EXDEV, 66 File handling
exec family, 8, 52, 25 1 access, 24, 80
exit, _exit, 52, 256 chmod, 24
Exiting processes, 256 chsize, 24, 1 5 1
exp, 46, 258 filelength, 24, 285
_expand, 48, 260 fstat, 24, 329
expl, 46, 258 include files, 23
Exponential functions isatty, 23, 437
exp, 258 locking, 23, 456
exp!, 258 mktemp, 23, 509
frexp, 3 1 8 remove, 23
frexpl, 3 1 8 rename, 24, 620
ldexp, 443 setmode, 24, 664
ldexpl, 443 stat, 24, 723
log, log I O, 459 umask, 24, 803
log!, log I 01, 459 unlink, 24
pow, 578 File permission mask. See Permission setting
powl, 578 File pointers
sqrt, 7 1 7 defined, 4 1
sqrt!, 7 1 7 positioning

F
fgetpos, 280
fseek, 322
fsetpos, 324
fabs, 46, 263 ftell, 332
fabsl, 46, 263 lseek, 468
Far pointers, 298 read and write operations, 43
_fcalloc, 1 36 rewind, 622
fclose, fcloseall, 37, 265 tell, 788
fcvt, 22, 267 File status information, 329, 723
fdopen, 37, 269 filelength, 24, 285
feof, 37, 272 fileno, 37, 287
ferror, 37, 274 Files
_fexpand, 260 changing size, 1 5 1
fflush, 37, 276 closing, 43, 1 6 1
_ffree, 48, 3 1 0 creating, 1 7 1 , 523, 704
834 Microsoft C Run-Time Library Reference

Files (continued) Formatted l/O


deleting, 6 1 9, 809 cprintf, 1 68
determining length, 285 cscanf, 1 73
locking, 456 fprintf, 303
modifying names, 509 fscanf, 320
names, 8 printf, 580
obtaining status, 329, 723 scanf, 630
opening sprintf, 7 1 5
creat, 1 7 1 sscanf, 720
input and ouput, 42 vfprintf, vprintf, vsprintf, 8 1 7
open, 523 FP_OFF, FP_SEG, 59, 298
sopen, 704 fpos_t type, 69
reading characters, 605 _fpreset, 47, 300
renaming, 620 fprintf, 8, 38, 303
setting modification time, 8 1 1 fputc, fputchar, 38, 305
writing characters, 826 fputs, 38, 307
find_t structure, 69 fread, 38, 308
Floating point _frealloc, 607
control word, 1 63 free, 48, 3 1 0
errors, 300 _freect, 48, 3 1 3
math package freopen, 38, 3 1 5
_clear87, 1 5 3 frexp, 47, 3 1 8
_control87, 1 63 frexpl, 47, 3 1 8
_fpreset, 300 fscanf, 8 , 38, 320
reinitialization, 300 fseek, 38, 322
_status87, 725 fsetpos, 38, 324
numbers, conversion to strings, 243, 267, 340 _fsopen, 38, 326
routines, 1 5 fstat, 24, 329
status word, 1 53 , 725 _fstrcat, 727
_floodfill,_floodfill_w, 30, 288 _fstrchr, 729
floor, 47, 290 _fstrcmp, 73 1
floor! , 47, 290 _fstrcpy, 734
flushall, 37, 292 _fstrcspn, 736
Flushing buffers, 276, 292 _fstrdup, 740
_fmalloc, 49, 476 _fstricmp, 746
_fmemccpy, 20, 487 _fstrlen, 748
_fmemchr, 20, 489 _fstrlwr, 750
_fmemcmp, 49 1 _fstmcat, 752
_fmemcpy, 20, 494 _fstmcmp, 754
_fmemicmp, 20, 497 _fstrncpy, 756
_fmemmove, 20, 501 _fstrnicmp, 758
_fmemset, 20, 504 _fstrnset, 759
fmod, 47, 293 _fstrpbrk, 76 1
_fmode variable, 66 _fstrrchr, 763
fmodl, 47, 293 _fstrrev, 765
_fmsize, 49, 5 1 9 _fstrset, 767
Fonts _fstrspn, 769
bit-mapped, 656 _fstrstr, 77 1
functions (l ist), 32
fopen, 37, 295
Index 835

_fstrtok, 778 Global variables (continued)


_fstrupr, 780 errno
ftell, 38, 332 described, 65
ftime, 6 1 , 334 perror, 53.8
_fullpath, 336 strerror, 742
Functions _fmode, 66
declarations, 7-9 _osmajor, 67
vs. macros, 1 0- 1 2 _osminor, 67
fwrite, 3 8 , 338 _psp, 68
sys_errlist
G described, 65
perror, 538
gcvt, 22, 340 strerror, 742
_getactivepage, 342 sys_nerr, 65, 538, 742
_getarcinfo, 344 timezone, 64, 799
_getbkcolor, 29, 345 tzname, 64, 799
getc, getchar, 38, 346 gmtime, 6 1 , 394
getch, getche, 44, 348 Goto, nonlocal, 463, 660
_getcolor, 29, 350 Graphics
_getcurrentposition, _getcurrentposition_w, 30, 352 attributes, 29
getcwd, 23, 354 color selection, 29, 647
_getdcwd, 356 configuration, 26, 680, 690
_getdrive, 359 coordinates, 26, 650, 686, 688
getenv, 360 font functions (list), 32
_getfillmask, 29, 362 image transfer, 3 1
_getfontinfo, 364 low-level palettes, 28
_getgtextextent, 365 output, 245, 449, 5 1 7, 6 1 0
_getgtextvector, 366 parameters, 652, 654, 66 1
_getimage, _getimage_w, _getimage_wxy, 32, 367 presentation graphics, 33-34, 540, 544, 546, 550
_getlinestyle, 29, 370 text output, 30
_getphyscoord, 27, 372 text support
getpid, 52, 373 _gettextwindow, 38 1
_getpixel, _getpixel_w, 30, 374 _scrolltextwindow, 635
gets, 38, 376 _settextrows, 675
_gettextcolor, 3 1 , 377 _settextwindow, 677
_gettextcursor, 378 _setvideomoderows, 684
_gettextposition, 3 1 , 379 _setwindow, 69 1
_gettextwindow, 3 8 1 _ wrapon, 824
_getvideoconfig, 27, 382 Greenwich mean time, 394
_getviewcoord, _getviewcoord_w, _grstatus, 396
_getviewcoord_wxy, 27, 386
_getvisualpage, 388 H
getw, 38, 389
_getwindowcoord, 26, 39 1 halloc, 48, 400
_getwritemode, 392 Handle. See File handles
Global variables _harderr, 59
accessing, 63 _hardresume, 59
_amblksiz, 63 _hardretn, 59
daylight, 64, 799 Header files. See Include files
_doserrno, 65 Heap consistency check
environ, 67, 360, 592 _bheapchk, 409
_bheapmin, 4 1 1
836 Microsoft C Run-Time Library Reference

Heap consistency check (conti1111ed) Interrupt signals, 696


_theapchk, _heapchk, _nheapchk, 409 Interrupts. See DOS interrupts, invoking
_theapmin, _heapmin, _nheapmin, 4 1 1 1/0
_heapadd, 406 See also Formatted 1/0
_heapchk, 409 buffered, 37
_heapmin, 4 1 1 console and port
_heapset, 4 1 2 cgets, 44, 1 4 1
_heapwalk, 4 1 5 cprintf, 44 , 1 68
hfree, 49, 4 1 9 cputs, 1 70
_huge data items, 1 6- 1 7 cscanf, 44, 1 73
Hyperbolic described, 35
cosine, 1 66 getch, getche, 44, 348
sine, 702 include files, 44
tangent, 786 inp, inpw, 44, 425
hypot, 47, 42 1 kbhit, 44, 440
Hypotenuse, 42 1 outp, outpw, 44, 532
hypotl, 47, 42 1 putch, 44, 59 1
ungetch, 44, 807
I low-level
close, 42, 1 6 1
IEEE format, converting double-precision to Microsoft creat, 42, 1 7 1
binary, 1 8 1 described, 35
_imagesize, _imagesize_w , _imagesize_wxy, 32, 423 dup, dup2, 42, 24 1
#include directive, 6 eof, 42, 249
Include files error handling, 43
buffer manipulation routines, 20 include files, 42
character classification, conversion, 22 )seek, 42, 468
console and port 1/0, 44 open, 42, 523 ·

Contents, 5, 7 read, 42, 605


data conversion, 22 sopen, 42, 704
directory control, 23 tell, 42, 788
DOS interface routines, 57 write, 42, 826
file handling, 23 stream, 35-36
low-level 1/0, 42 IO.H, 23, 42
math routines, 46 isalnum, isdigit, isgraph, 2 1 , 434
memory allocation, 48 isalpha, isascii, iscntrl, 434
naming conventions, vi isatty, 24, 437
process control, 5 1 isdigit, 434
processor calls, 6 1 islower, isupper, isxdigit, 2 1 , 434
reasons for using, 6 isprint, 2 1 , 434
searching and sorting, 55 ispunct, 2 1 , 434
stream 1/0, 36 isspace, 2 1 , 434
string manipulation, 55 Italic letters, use of, ix
time routines, 6 1 itoa, 22, 438
inp, inpw, 44-45, 425
int86, 59, 426
int86x, 59, 428
J
intdos, 59, 430 jO, j I , jn, 1 07
intdosx, 59, 432 JOI, j I I, jnl, 1 07
Integers jmp_buf type, 69
conversion to strings, 438
long, conversion to strings, 47 1 , 80 1
Index 837

K Low-level graphics (continued)


output (continued)
kbhit, 44, 440 _rectangle, _rectangle_w, _rectangle_wxy,
Keystroke, testing, 440 30, 6 1 0
_setwritemode, 695
L palettes, 28
parameters, 30
labs, 44 1 physical coordinates, 26
ldexpl, 47, 443 text support (list), 30
ldiv, 445 view coordinates, 26
ldiv_ttype, 69 window coordinates, 26
lfind, 55, 447 _Irotl, 465
Library (.LIB) files _lrotr, 465
contents, 5 !search, 55, 466
default, 6 lseek, 42, 468
GRAPHICS.LIB, 6 ltoa; 22, 47 1

M
use, 6
Library routines, calling, 5
Lines
reading, 282, 376 _makepath, 473
writing, 596 Macros, 1 0- 1 2
_Iineto, 30, 449 malloc, 49, 476
_Iineto_w, 30, 449 MALLOC.H, 48
Local time corrections, 64, 454, 799 Mask. See Permission setting
localeconv, 45 1 MATH.H, 22, 46
Localization matherr
localeconv, 45 1 described, 480
setlocale, 662 use, 47
localtime, 6 1 , 454 _matherrl, 480
locking, 24, 456 max, 484
log, log 10, 459 _memavl , 49, 485
Logarithmic functions, 47, 459 memccpy, 20, 487
log!, log I OI, 459 memchr, 20, 489
long double functions, 46 1 memcmp, 20, 49 1
Long integers, conversion to strings, 47 1 memcpy, 20, 494
longjmp, 463 memicmp, 20, 497
Low-level graphics _memmax, 49, 499
See also individualfunction names memmove, 20, 50 1
color selection, 28-29 Memory allocation
configuration, 26 _amblksiz, 63
coordinates, 26 available memory, determination, 3 1 3
font functions. See Fonts _bcalloc, 1 36
image transfer, 3 1 _bfree, 3 1 0
output _bfreeseg, 1 1 0
_arc, _arc_w, _arc_wxy, 30, 86 _bheapadd, 406
_ellipse, _ellipse_w, _ellipse_wxy, 30, 245 _bheapchk, 409
_getarcinfo, 344 _bheapmin, 41 1
_getwritemode, 392 _bheapseg, 1 1 2
_grstatus, 396 _bheapset, 41 2
_lineto, _lineto_w, 30, 449 _bheapwalk, 4 1 5
_pie, _pie_ w, _pie_ wxy, 30, 567 _bmalloc, 476
_pol ygon, _pol ygon_w, _pol ygon_wxy, 574 _bmsize, 5 1 9
838 Microsoft C Run-Time Library Reference

Memory allocation (ca11ti1111ed) _moveto_w, 30, 5 1 7


_brealloc, 607 MS C 4.0, differences, puts, 596
calloc, 1 36 _msize, 49, 5 1 9

N
_expand, 260
_fcalloc, 1 36
_ffree, 3 1 0
_fueapchk, 409 _ncalloc, 1 36
_fueapmin, 4 1 1 NDEBUG, 92
_fueapset, 4 1 2 _nexpand, 260
_fueapwalk, 4 1 5 _nfree, 48, 3 1 0
_fmalloc, 476 _nheapchk, 48, 409
_fmsize, 5 1 9 _npeapmin, 4 1 1
_frealloc, 607 _nileapset, 49, 4 1 2
free, 3 1 0 _nheapwalk, 49, 4 1 5
_freect, 3 1 3 _nmalloc, 49, 476
halloc, 400 _nmsize, 49, 5 1 9
_heapadd, 406 Nonlocal goto, 463, 660
_heapchk, 409 _nrealloc, 607
_heapmin, 4 1 1 _nstrdup, 740
_heapset, 4 1 2 Null pointer, 37
_heapwalk, 4 1 5
hfree, 4 1 9
malloc, 476
0
_memavl, 485 Object (.OBJ) files, 6
O_BINARY, 66
oflag. See Open flag
.:.memmax, 499
_msize, 5 1 9
_ncalloc, 1 36 onexit, 52, 52 1
_nfree, 3 1 0 open, 8, 42, 523
_nheapchk, 409 Open flag, 523, 704
_nheapmin, 41 1 Operating system, 1 4
_nheapset, 4 1 2 Optional items, ix
_nheapwalk, 4 1 5 _osmajQr variable, 67
_nmalloc, 476 _osminor variable, 67
_nmsize, 5 1 9 _outgtext, 32, 527
_nrealloc, 607 _outmem, 530
realloc, 607 outp, outpw, 44-45, 532
routines and uses (list), 48 Output. See 1/0
stackavail, 722 _outtext, 3 1 , 535
MEMORY.ff, 20 OVERFLOW, 480
memset, 20, 504 Overlapping moves, 494
Microsoft Windows, 25 Overlay, of parent process, 707
min, 506
mkdir, 23, 507
mktemp, 24, 509
p
mktime, 6 1 , 5 1 1 Palettes, low-level, 28
Model-independent memory routines, 20 Parameters, variable-length number, 62, 8 1 7
modf, 47, 5 1 3 Parent process
modfl, 47, 5 1 3 cwait, 1 77
Modification time, 8 1 1 described, 25 1
Monofont, use of, x overlay and suspension, 707
movedata, 5 1 5 wait, 820
_moveto, 30, 5 1 7 Path names, 9
Index 839

_pclose, 537 Process control


Pennission setting abort, 5 1 , 76
access, 80 atexit, 5 1 , 96
changing, 1 49 _cexit, _c_exit, 1 40
described, 1 7 1 cwait, 1 77
mask, 803 exec family, 52
open, 523 exit, _exit, 52, 256
sopen, 704 getpid, 52, 373
umask, 803 include files, 5 1
perror, 1 3, 538 onexit, 52, 52 1
_pg_analyzechart, 34, 540 · raise, 52, 60 1

!>L
_pg_analyzechartms, 34, 540 signal, 52, 696
_ analyzepie, 34, 543 spawn family, 53
_pg_analyzescatter, 34, 544 system, 53, 784
_pg_analyzescattenns, 34, 544 wait, 820
_pg_chart, 33, 546 Process ID, 373
_pg_chartms, 33, 546 PROCESS.ff, 5 1
_pg_chartpie, 33, 549 Processor calls, include files, 6 1
_pg_chartscatter, 33, 550 Program segment prefix (PSP), 68
_pg_chartscattenns, 33, 550 Pseudorandom integers, 603, 7 1 8
_pg_defaultchart, 33, 552 _psp, 68
_pg_getchardef, 34, 554 putc, putchar, 38, 589
_pg_getpalette, 34, 555 putch, 44, 59 1
_pg_getstyleset, 34, 558 putenv, 592
_pg_hlabelchart, 34, 559 _putimage, _putimage_w, 32, 594
_pg_initchart, 33, 560 puts, 38
_pg_resetpalette, 34, 56 1 putw, 38, 597
_pg_resetstyleset, 34, 562
_pg_setchardef, 34, 563
_pg_setpalette, 34, 564
Q
_pg_setstyleset, 34, 565 qsort, 55, 599
_pg_vlabelchart, 34, 566 Quick sort algorithm, 599
_pie , _pie_w, _pie_wxy, 30, 567 Quotation marks, use of, x
_pipe, 570
Pipes ·
_pclose, 537
R
_pipe, 570 raise, 52, 60 I
_popen, 576 rand, 603
PLOSS, 480 Random access
Pointers, long, 298 fgetpos, 280
_po lygon, _polygon_w, _polygon_wxy, 574 fseek, 322
_popen, 576 fsetpos, 324
Port l/O. See 1/0, console and port ftell, 332
pow, 47, 578 lseek, 468
Predefined rewind, 622
handles, 43 tell, 788
stream pointers, 39 Random number generator, 603, 7 1 8
types. See Standard types read, 42, 605
printf, 38, 580 Read access. See Pennission setting
Printing. See Write operations
840 Microsoft C Run-Time Library Reference

Read operations Searching and sorting (continued)


binary int value, 389 lsearch, 466
characters qsort, 55, 599
from file, 605 seed, 7 1 8
from stdin, 278, 346 Segmerfi registers, 640
from stream, 278, 346 segread, 59, 640
from console, 1 4 1 , 1 73, 348, 440 _selectpalette, 28, 642
formatted _setactivepage, 26, 645
cscanf, 1 73 _setbkcolor, 29, 647
fscanf, 320 setbuf, 38, 40, 648
scanf, 630 _setcliprgn, 650
sscanf, 720 _setcolor, 29, 652
line _setfillmask, 29, 654
from stdin, 376 _setfont, 32, 656
from stream, 282 _setgtextvector, 659
from port, 425 setjmp, 660
realloc, 49, 607 _setlinestyle, 29, 66 1
Reallocation setlocale, 662
_brealloc, 607 setmode, 24, 664
_expand, 260 _setpixel, _setpixel_w, 29, 666
_frealloc, 607 _settextcolor, 3 l , 668
_nrealloc, 607 _settextcursor, 67 1
realloc, 49, 607 _settextposition, 673
_rectangle, _rectangle_w, _rectangle_ wxy, 30, 6 l 0 _settextrows, 675
Redirection, 40, 43-44, 3 1 5 _settextwindow, 3 l , 677
_registerfonts, 32, 6 1 2 setvbuf, 38, 40
REGS type, 70 _setvideomode, 26, 680
Remainder function, 293 _setvideomoderows, 684
_remapallpalette, 28, 6 1 3 _setvieworg, 27, 686
_remappalette, 28, 6 1 3 _setviewport, 27, 688
remove, 24, 6 1 9 _setvisualpage, 26, 690
rename, 24, 620 _setwindow, 27, 69 1
Reversing strings, 765 _setwritemode, 695
rewind, 38, 622 signal
rmdir, 23, 624 described, 53, 696
rmtmp, 38, 626 raise, 60 1
_rotl, 628 SIGNAL.ff, 5 1
_rotr, 628 sin, sinh, 47, 702
S ine, 702
s SING, 480
sin!, sinhl, 47, 702
scanf, 8, 38, 630 size_t type, 70
Scanning. See Read operations Small capital letters, use of, x
_scrolltextwindow, 635 sopen, 8, 42, 704
SEARCH.ff, 55 Sorting. See Searching and sorting
_searchenv, 638 spawn family
Searching and sorting argument-type-checking limitations, 8, 707
bsearch, 55, 1 3 2 described, 707
include files, 5 5 use, 53
lfind, 447 _splitpath, 7 1 3
l find, !search, 55 sprintf, 8 , 7 1 5
sqrt, 47, 7 1 7
Index 841

sqrt!, 47, 7 1 7 stdaux, stderr, stdio


Square-root function, 7 1 7 buffering, 40
srand, 7 1 8 described, 40
SREGS type, 70 file handle, 43
sscanf translation mode, changing, 664
described, 720 STDIO.H, 36
type checking, 8 stdout, stdpm
use, 38 buffering, 40
Stack checking, 1 2 described, 40
Stack environment file handle, 43
restoring, 463 translation mode, changing, 664
saving, 660 Streat, 55 , 727
stackavail, 49, 722 strchr, 55, 729
Standard auxiliary. See stdaux, stderr, stdin strcmp, 55, 73 1
Standard error. See stdaux, stderr, stdin strcoll, 733
Standard input. See stdaux, stderr, stdio strcpy, 55, 734
Standard output. See stdout, stdpm strcspn, 55, 736
Standard print. See stdout, stdpm _strdate, 6 1 , 738
Standard types strdup, 55, 740
clock_t, 68
See also I/0, console and port
Stream I/0
complex, 68
diskfree_t, 69 buffering, 40
diskinfo_t, 69 clearerr, 1 55
div_t, 69 described, 35
dosdate_t, 69 error handling, 4 1
DOSERROR, 69, 239 fclose, fcloseal l , 265
dostime_t, 69 fdopen, 269
exception, 69, 480 feof, 272
FILE, 69 ferror, 274
find_t, 69 fflush, 276
fpos_t, 69 fgetc, fgetchar, 278
j mp_buf, 69 fgetpos, 280
ldiv_t, 69 fgets, 282
l isted, 68 fileno, 287
REGS, 70 flushall, 292
size_t, 70 fopen, 295
SREGS, 70 fprintf, 303
stat, 723 fputc, fputchar, 305
time_t, 70, 1 82 fputs, 307, 596
timeb, 70, 334 fread, 308
tm, 70, 394 freopen, 3 1 5
utimbuf, 70, 8 1 1 fscanf, 320
va_l ist, 70 fseek, 322
stat routine fsetpos, 324
described, 723 _fsopen, 326
use, 24 ftell, 332
stat type fwrite, 338
described, 70 getc, getchar, 346
fstat, 329 gets, 376
_status87, 725 getw, 389
printf, 580
putc, putchar, 589
842 Microsoft C Run-Time Library Reference

Stream 1/0 {continued) _strerror, 742


putw, 597 · strftime, 744
rewind, 622 stricmp, 55, 746
routines and uses (l ist), 37 String manipulation
scanf, 630 _fstrcat, 727
setbuf, 648 _fstrchr, 729
sprintf, 7 1 5 _fstrcmp, 73 1
sscanf, 720 _fstrcpy, 734
tempnam, tmpnam, 38 _fstrcspn, 736
ungetc, 805 _fstrdup, 740
vfprintf, vprintf, vsprintf, 8 1 7 _fstricmp, 746
Stream pointer, 37 _fstrlwr, 750
Streams _fstrncat, 752
appending, 295, 3 1 5, 326 _fstmcmp, 754
buffering, 648 _fstrncpy, 756
clearing errors, 1 55 _fstmicmp, 758
closing, 4 1 , 265 _fstrnset, 759
file handles for, 287 _fstrpbrk, 76 1
file pointer position _fstrrchr, 763
fseek, 322 _fstrrev, 765
fsetpos, 324 _fstrset, 767
ftell, 332 _fstrspn, 769
fgetpos, 280 _fstrstr, 77 1
rewind, 622 _fstrtok, 778
formatted 1/0 _fstrupr, 780
printf, 580 _nstrdup, 740
scanf, 630 routines and uses (list), 55
sprintf, 7 1 5 strcat, 727
sscanf, 720 strchr, 729
stream, 303, 320 strcmp, 73 1
vprintf, 8 1 7 strcoll, 733, 744
opening, 39, 269, 295, 326 strcpy, 734
reading strcspn, 736
binary int value, 389 strdup, 740
characters, 278, 346 stricmp, 746
data items, 308 strlwr, 750
lines, 282, 376 stmcat, 752
reopening, 3 1 5 stmcmp, 754
rewinding, 622 strncpy, 756
stdaux, stderr, stdin, 40 stmicmp, 758
stdout, stdpm, 40 stmset, 759
translation mode. See Binary, mode strpbrk, 76 1
ungetting characters, 805 strrchr, 763
writing strrev, 765
binary int value, 597 strset, 767
characters, 305, 5 89 strspn, 769
data items, 338 strstr, 77 1
lines, 596 strtok, 778
strings, 307 strupr, 780
strerror, 1 3, 55, 742 strxfrm, 782
STRING.ff, 55
Index 843

Strings SYS\TIMEB.H, 6 1
comparing, 73 1 , 733, 744, 746, 754, 758 SYS\TYPES, 6 1
concatenating, 752 SYS\UTIME.H, 6 1
converting sys_errlist
to floating-point values, 98 described, 65
to lowercase, 750 system error messages, 538, 742
to uppercase, 780 sys_nerr, 65, 538, 742
copying, 734, 740, 756 system, 53, 784
initializing, 759, 767 System calls. See DOS system calls
reading from console, 1 4 1 System time. See Time

T
reversing, 765
searching
_fstrchr, 729
_fstrcspn, 736 tan, tanh, 47, 786
_fstrpbrk, 76 1 Tangent, 786
_fstrrchr, 763 tan!, tanhl, 47, 786
_fstrspn, 769 tell, 42, 788
_fstrstr, 77 1 tempnam, tmpnam, 38, 790
_fstrtok, 778 Terminal capabilities, 437
strchr, 729 Text mode
strcspn, 736 vs. binary, 35
strpbrk, 76 1 described, 66, 523
strrchr, 763 setmode, 664
strspn, 769 sopen, 704
strstr, 77 1 stream 1/0, 269, 296, 3 1 5, 327
strtok, 778 Threads
writing _beginthread, 103
to console, 1 68, 1 70 DosExit, 248
to stream, 307 _endthread, 248
strlen, 56 termination, 248
strlwr, 56, 750 Time ·

stmcat, 56, 752 conversion


stmcmp, 56, 754 long integer to string, 1 75
stmcpy, 56, 756 long integer to structure, 454
stmicmp, 56, 758 structure to s tring, 88
stmset, 56, 759 functions, 6 1
strpbrk, 56, 76 1 global variables, setting, 799
strrchr, 56, 763 local time, correcting, 454
strrev, 56, 765 obtaining, 334, 793
strset, 56, 767 routines
strspn, 56, 769 asctime, 88
strstr, 56, 77 1 clock, 1 59
_strtime, 6 1 , 773 ctime, 1 75
strtod, 22, 775 difftime, 1 82
strtok, 56, 778 ftime, 334
strtol, 23, 775 gmtime, 394
_strtold, 23, 775 (list), 60
strtoul, 23, 775 localtime, 454
strupr, 56, 780 mktime, 5 1 1
strxfrm, 782 time, 793
swab, 783 tzset, 799
SYS\STAT.H, 23 utime, 8 1 1
844 Microsoft C Run-Time Library Reference

Time (continued) Uppercase, use of, ix


time differences, computing, 1 82 utimbuf type, 70, 8 1 1
time function, 793 utime, S i l
TIME.H, 6 1
time_t type, 70, 1 82
timeb type, 70, 334
v
timezone variable, 64, 799 va_arg, va_end, va_start, 62
TLOSS, 480 va_list type, 70
tm type, 70, 394 Version number (DOS), 67
tmpfile, 39 vfprintf, vprintf, vsprintf, 39, 8 1 7

w
tmpnam, 790
toascii, 2 1 , 796
Tokens, finding in strings, 778
wait, 820
Word. See Binary, int
_tolower, _toupper, 2 1 , 796
tolower, toupper, 2 1 , 796
_toupper, 796 _wrapon, 3 1 , 824
Trigonometric functions write, 42, 826
acos, 82 Write access. See Permission setting
acosl, 82 Write operations
asin, 90 binary int value to stream, 597
asinl, 90 character
atan, atan2, 94 to console, 1 68
atanl, atan21, 94 to file, 826
cos, cosh, 1 66 to stdout, 305, 589
hypot, 42 1 to stream, 305, 589, 805
hypotl, 42 1 to console, 1 69, 1 70, 59 1
sin, sinh, 702 data items from stream, 338
sinl, sinhl, 702 formatted
tan, tanh, 786 cprintf, 1 68
tanl, tanhl, 786 printf, 580
Type checking sprintf, 7 1 5
function declarations, 7-8 stream 1/0, 303
include files, 7 vprintf, 8 1 7
variable arguments, 8 line to stream, 596
TZ environment variable to port, 532
default value, 64 string to stream, 307
focaltime, 454
tzset, 799
tzname variable, 64, 799
x
tzset, 799 XENIX, 9

u y
ultoa, 23, 801 yO, y l , yn, 1 07
umask, 24, 803 _yOI , _y l l, _ynl, 1 07
UNDERFLOW, 48 1
UNIX, 9
ungetc, 39, 805
ungetch, 44, 807
Universal Coordinated Time, 6 1
unlink, 24, 809
_unregisterfonts, 32, 8 1 0
. ... . .

· : -- . •

,. _ ,.

... .
,.
... �r .

. -;· .
: . ­
- �· :

- . :_.'--

: ·: ,
.··

· _· · , , · ·
,:· ·
. \" · ._; · "
' . .. .... . :.. . ·

. �....

.� - ·.

,;"
. . -. :,;
' . ·

' - : .. _

. . . -�,
•ictosottI.Jniversity'
Training That Makes Sense
At Microsoft University, we believe the proof of excellent PLOT YOUR OWN COURSE
training is in a student's ability to apply it. That' s not a Our curriculum allows you to customize your course of
complicated philosophy. And, it's not a new idea. But it study from timely, fundamental courses for support
does represent an uncommon approach to training in the personnel to highly focused, technical courses for sophisti­
'
microcomputer industry, mainly because it requires cated developers . We offer courses on Microsoft Windows;"
extensive technical and educational resources, as well as Microsoft OS/2, Microsoft OS/2 Presentation Manager,
leading-edge programming expertise. Microsoft LAN Manager, Microsoft SQL Server, and
When you attend Microsoft University, our courses Microsoft C.
take you to the heart of our microcomputer software
architecture. Lab sessions provide practical, hands-on TIME IS OF THE ESSENCE
experience and show you how to develop and debug soft­ To find out more about Microsoft University, call our
ware more efficiently. Our qualified instructors explain the registrar at (206) 867-5507, extension 605 . We 'll send you
philosophy and principles that drive our systems designs. our current course schedule, which describes our courses in
detail and provides complete registration information for our
OUR LAB-BASED DISTINCTION campus facilities in Seattle, Boston, and Baltimore, as well
Because our courses are lab-based, when you graduate from as our growing, nationwide network of Microsoft University
Microsoft University, you 'll begin applying what you 've Authorized Training Centers.
learned immediately. Throughout our courses, you'll be de­ Microsoft University also offers our courses on-site at
signing a software application that demonstrates the your location, when it's convenient for you and your staff.
principles you've just learned in class. To find out more about hosting an on-site course, contact
The power of our sheepskin pays off in the increased the Microsoft University Sales Manager at (206) 867-5507,
knowledge and time savings as soon as you begin your next extension 605 .
development project. Our courses fill up quickly-so don't delay.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

I'D LIKE TO KNOW MORE ! PLEASE PRINT

0 Please send me the most current course schedule.


0 Please send me the Microsoft University catalog.
0 Please have a representative call me regarding an on-site course for
Name:

Job Title!Fu11ction:

0 Please send me more information on the Authorized Training Center


Course / Topic Company (ifapp/i<-ab/e):

Street Address:

0 Please send me the latest information on The Lecture Series :"*


program.

0 Please send me more information on the following Microsoft City: State: Zip

0 MS® OS/2 0 Microsoft SQL Server


University courses:

0 MS OS/2 Presentation Manager 0 Microsoft Windows'"


Daytime Pho11e:

Please clip along dotted line and mail to:

0 MS LAN Manager 0 Microsoft C


llllictOsoniversity'
ttlJ
0 Microsoft University Technical Training Video Courses
When it's available, please send me information on:

One Microsoft Way, Redmond, WA 98052-6399


Co11rse I Topi<' Microsoft. the Microsoft logo, and MS are registered trademarks, and Windows and

Seminars and lectures on highlyfocused topics


The Lecture Series are trademarks of Microsoft Corporation.
*

X605
2'.·

-;. . . " ·
. �:· . �._ � .
;: : · ; ·_;
Other Titles from Microsoft Press

MICROSOFT® C RUN-TIME LIBRARY: PROGRAMMER 'S QUICK


REFERENCE
Kris Jamsa
This handy guide provides instant access to concise information on more than 250 of the most commonly used
Microsoft C and Microsoft QuickC Run-Time Library functions-a welcome reference for any C programmer. Jamsa
provides a description of each function along with exact syntax, required include files, programming examples, and a
listing of related titles.
272 pages, softcover 4 3/4 x 8 $7.95 Order Code: QRCRU

VARIATIONS IN C, 2nd ed.


Building Professional Applications with Microsoft® C
Steve Schustack
If you're a programmer with a background in structured languages (although not necessarily in C), VARIATIONS IN
C will show you how to develop high-quality applications software. Among the hundreds of C books, this is one of
the few that show, step by step, the design and implementatiQn of a large, commercial-quality application. Schustack
offers an intermediate-level discussion of data types, operators, control-flow statements, data handling, and functions.
Throughout, he incorporates details on Microsoft C Compiler version 5 . 1 and the ANSI-approved Standard C (with
helpful notes on using C compilers that don't conform to the ANSI standard). The heart of the book is the develop­
ment of a sophisticated vendor order-entry application with over 1 500 lines of code; many small businesses currently
use this program from VARIATIONS IN C.
448 pages, softcover 7 3/s x 9 1/4 $22.95 Order Code VAC2

ADVANCED MS-DOS® PROGRAMMING, 2nd ed.


The Microsoft® Guide for Assembly Language and C Programmers
Ray Duncan
This is the preeminent source of MS-DOS information for assembly language and C programmers-now completely
updated with new data and programming advice covering the ROM BIOS for the IBM PC, PC/AT, PS/2, and related
peripherals (including disk drives, video adapters, and pointing devices); MS-DOS through version 4; "well-behaved"
vs. "hardware-dependent" applications; version 4 of the Lotus/Intel/Microsoft Expanded Memory Specification; and
compatibility considerations for OS/2. Duncan, a DOS authority and noted columnist, explores key programming
topics, including character devices, mass storage, memory allocation and management, and process management. In
addition, a healthy assortment of updated assembly language and C listings ranges from code fragments to complete
utilities. The examples, from programming samples to full-length utilities, are instructive and extremely useful. All
were developed using Microsoft Macro Assembler version 5 . 1 and Microsoft C Compiler version 5 . 1 . And the
reference section, detailing each MS-DOS function and interrupt, is virtually a book within a book. ADVANCED
MS-DOS PROGRAMMING-your key to fast, efficient, robust programs.
688 pages, softcover 7 3/s x 9 1/4 $24.95 Order Code ADMSP2
GRAPHICS PROGRAMMING WITH MICROSOFT® C AND MICROSOFT
QUICKC®
Kris Jamsa
The built-in graphics libraries in Microsoft C and QuickC present extraordinary opportunities for today' s program­
mer. They offer a great timesaving way to enhance your programs with clean, dynamic graphical elements-from
simple shapes to 3-D images. If you 're a beginning- to intermediate-level C programmer, this book can show you the
most effective ways to use the rich resources of these built-in libraries. Up-to-date information, authoritative advice,
and a wealth of examples make GRAPHICS PROGRAMMING WITH MICROSOFf C AND MICROSOFf
QUICKC a must-have reference for your C programming.
624 pages, softcover 7 3/s x 9 1/4 $24.95 Order Code GRPRC

MICROSOFT® QUICKC® PROGRAMMER' S TOOLBOX


An Essential Collection of More than 200 Programs, Functions, and Utilities for
Supercharging QuickC Programs
John Clark Craig
Save hours of development time and sharpen your QuickC programming skills with this powerful collection of
solutions to common and uncommon programming problems. The toolbox functions offer fine examples of structured
programming-a gold mine for novice and intermediate QuickC programmers. The functions are organized into
modules that you can apply immediately to your own programming tasks. Included in the book are programs,
functions, and utilities that enable you to access, use, and control a mouse in creative ways, develop and customize
menus, draw and fill geometric figures using QuickC 's graphics functions, format text files for PostScript printing,
access DOS and BIOS functions through software interrupts, work with fractions and complex numbers, and
manipulate strings in a variety of ways. MICROSOFf QUICKC PROGRAMMER 'S TOOLBOX is a valuable
resource that you're guaranteed to open again and again.
544 pages, softcover 7 3/s x 9 1/4 $22.95 Order Code QCPRTO

MICROSOFT® QUICKC®: PROGRAMMER' S QUICK REFERENCE


Covers Microsoft QuickC Version 2
Kris Jamsa
Whether you ' re new to Microsoft QuickC or a veteran, here' s concise, handy information you 'll want at your
fingertips while you program. This one-of-a-kind reference offers instant refreshers and quick tutorials. In addition to
providing a brief overview of QuickC-;-its graphical interface, compiler options, types, and pragmas-'-Jamsa covers
installing and starting QuickC, accessing QuickC Help, debugging programs, developing large programs and libraries
in QuickC, accessing any function in the run-time library, and more. A final section includes a complete listing of the
QuickC compiler error messages.
176 pages, softcover 4 3/4 x 8 $6.95 Order Code QRQC

Or call 1-800-MSPRESSfor ordering information or placing credit card orders.


Microsoft Press books are available wherever quality computer books are sold.

Please refer to BBK when placing your order.

You might also like